无论如何,当你想将MyOwnType存储到文件时,MyOwnType必须是NSObject的子类并且符合NSCoding协议。像这样:
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")
}
}
那么,这里是Dictionary:
var dict = [Int : [Int : MyOwnType]]()
dict[1] = [
1: MyOwnType(name: "foobar"),
2: MyOwnType(name: "bazqux")
]
那么,你的问题来了:
将 swift 字典写入文件
你可以用NSKeyedArchiver写,NSKeyedUnarchiver读:
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`
但在你的问题正文中:
如何在 swift 中将其写入/读取到 plist 文件?
事实上,NSKeyedArchiverformat is binary plist。但是,如果您希望该字典作为 plist 的值,您可以使用 NSKeyedArchiver 将 Dictionary 序列化为 NSData:
// archive to data
let dat:NSData = NSKeyedArchiver.archivedDataWithRootObject(dict)
// unarchive from data
let dict2 = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Int : [Int : MyOwnType]]