快速将NSDictionaries写入文件有局限性。根据我从api文档中学到的知识和这个答案,键类型应该是NSString,值类型也应该是NSx类型,并且Int,String和其他swift类型可能不起作用。问题是,如果我有一个像这样的字典:Dictionary<Int,Dictionary<Int, MyOwnType>>如何快速将其写入plist文件或从plist文件读取?
Dictionary<Int,Dictionary<Int, MyOwnType>>
无论如何,当您要存储MyOwnType到文件时,它MyOwnType必须是协议的子类NSObject并符合NSCoding协议。像这样:
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:
Dictionary
var dict = [Int : [Int : MyOwnType]]() dict[1] = [ 1: MyOwnType(name: "foobar"), 2: MyOwnType(name: "bazqux") ]
所以,这是您的问题:
将快速字典写入文件
您可以NSKeyedArchiver用来写和NSKeyedUnarchiver阅读:
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`
但在您的问题中:
如何快速将其写入 plist 文件或从中读取?
实际上,NSKeyedArchiver format是二进制plist。但是,如果你想要的字典 作为plist中的一个值 ,你可以序列化Dictionary到NSData用NSKeyedArchiver:
NSData
// archive to data let dat:NSData = NSKeyedArchiver.archivedDataWithRootObject(dict) // unarchive from data let dict2 = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Int : [Int : MyOwnType]]