将swift词典写入文件

AKH*_*AKH 14 dictionary nsdictionary plist swift

在NSift中将NSDictionaries写入文件存在限制.基于我从api文档和这个stackoverflow答案中学到的东西,键类型应该是NSString,值类型也应该是NSx类型,Int,String和其他swift类型可能不起作用.问题是,如果我有一个字典,如:Dictionary<Int, Dictionary<Int, MyOwnType>>,如何在swift中写入/读取plist文件?

rin*_*aro 27

无论如何,当你想存储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")
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,这是Dictionary:

var dict = [Int : [Int : MyOwnType]]()
dict[1] = [
    1: MyOwnType(name: "foobar"),
    2: MyOwnType(name: "bazqux")
]
Run Code Online (Sandbox Code Playgroud)

所以,这是你的问题:

将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`
Run Code Online (Sandbox Code Playgroud)

但在你的问题正文中:

如何在swift中向/从plist文件中写入/读取它?

实际上,NSKeyedArchiver 格式是二进制plist.但是,如果你想要的字典作为plist中的一个值,你可以序列化DictionaryNSDataNSKeyedArchiver:

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

// unarchive from data
let dict2 = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Int : [Int : MyOwnType]]
Run Code Online (Sandbox Code Playgroud)