Writing swift dictionary to file

天大地大妈咪最大 提交于 2019-11-28 20:44:26
rintaro

Anyway, when you want to store MyOwnType to file, MyOwnType must be a subclass of NSObject and conforms to NSCoding protocol. like this:

class MyOwnType: NSObject, NSCoding {

    var name: String

    init(name: String) {
        self.name = name
    }

    required init(coder aDecoder: NSCoder) {
        name = aDecoder.decodeObjectForKey("name") as? String ?? ""
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(name, forKey: "name")
    }
}

Then, here is the Dictionary:

var dict = [Int : [Int : MyOwnType]]()
dict[1] = [
    1: MyOwnType(name: "foobar"),
    2: MyOwnType(name: "bazqux")
]

So, here comes your question:

Writing swift dictionary to file

You can use NSKeyedArchiver to write, and NSKeyedUnarchiver to read:

func getFileURL(fileName: String) -> NSURL {
    let manager = NSFileManager.defaultManager()
    let dirURL = manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false, error: nil)
    return dirURL!.URLByAppendingPathComponent(fileName)
}

let filePath = getFileURL("data.dat").path!

// write to file
NSKeyedArchiver.archiveRootObject(dict, toFile: filePath)

// read from file
let dict2 = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as [Int : [Int : MyOwnType]]

// here `dict2` is a copy of `dict`

But in the body of your question:

how can I write/read it to/from a plist file in swift?

In fact, NSKeyedArchiver format is binary plist. But if you want that dictionary as a value of plist, you can serialize Dictionary to NSData with NSKeyedArchiver:

// archive to data
let dat:NSData = NSKeyedArchiver.archivedDataWithRootObject(dict)

// unarchive from data
let dict2 = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Int : [Int : MyOwnType]]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!