首页 文章

将swift词典写入文件

提问于
浏览
13

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

1 回答

  • 25

    无论如何,当你想将 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文件中写入/读取它?

    事实上, NSKeyedArchiver format is binary plist . 但是如果你想要那个字典 as a value of plist ,你可以用 NSKeyedArchiver 序列化 DictionaryNSData

    // archive to data
    let dat:NSData = NSKeyedArchiver.archivedDataWithRootObject(dict)
    
    // unarchive from data
    let dict2 = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Int : [Int : MyOwnType]]
    

相关问题