Swift 4:向Plist添加词典

时间:2017-11-21 17:39:20

标签: ios swift xcode

所以,我有一个空的plist,我试图在plist中创建这些值

使用此代码:

 let dictionary:[String:String] = ["key1" : "value1", "key2":"value2", "key3":"value3"]

let documentDirectoryURL =  FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentDirectoryURL.appendingPathComponent("dictionary.plist")
if NSKeyedArchiver.archiveRootObject(dictionary, toFile: fileURL.path) {
    print(true)
}

if let loadedDic = NSKeyedUnarchiver.unarchiveObject(withFile: fileURL.path) as? [String:String] {
    print(loadedDic)   // "["key1": "value1", "key2": "value2", "key3": "value3"]\n"
}

这里的一切都很好,但问题是,当我点击我的xcode项目中的plist时,它是空的,这些值只打印而不是插入到plist中

3 个答案:

答案 0 :(得分:7)

NSKeyedUnarchiver是保存属性列表的错误方法。

有一个专用的结构PropertyListSerialization来加载和保存属性列表。

首先声明一个计算属性plistURL

var plistURL : URL {
    let documentDirectoryURL =  try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    return documentDirectoryURL.appendingPathComponent("dictionary.plist")
}

和两种加载和保存方法

func savePropertyList(_ plist: Any) throws
{
    let plistData = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
    try plistData.write(to: plistURL)
}


func loadPropertyList() throws -> [String:String]
{
    let data = try Data(contentsOf: plistURL)
    guard let plist = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String:String] else {
        return [String:String]()
    }
    return plist
}

创建字典并保存

do {
    let dictionary = ["key1" : "value1", "key2":"value2", "key3":"value3"]
    try savePropertyList(dictionary)
} catch {
    print(error)
}

要更新读取的值,请更新该值并将其保存回来

do {
    var dictionary = try loadPropertyList()
    dictionary.updateValue("value4", forKey: "key4")
    try savePropertyList(dictionary)
} catch {
    print(error)
}

答案 1 :(得分:2)

您是否尝试过使用PropertyListEncoder代替NSKeyedArchiver

do {
    try PropertyListEncoder().encode(dictionary).write(to: fileURL)
} catch {
    print(error)
}

解码:

do {
    let data = try Data(contentsOf: fileURL)
    try PropertyListDecoder().decode([String: String].self, from: data)
} catch {
    // Handle error
}

答案 2 :(得分:-1)

这是我的回答

 //MARK: User.plist Save & retrive data 
    func saveUserDataWithParams(userData: AnyObject) -> Void { 
        let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString 
        let path : NSString = documentsDirectory.appendingPathComponent("User.plist") as NSString 
        //userData.write(path as String, atomically: true) 
        userData.write(toFile: path as String, atomically: true) 
    } 

    func getUserPlistData() -> NSMutableDictionary { 
        let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString 
        let path : NSString = documentsDirectory.appendingPathComponent("User.plist") as NSString 

        let fileManager = FileManager.default 
        if (!(fileManager.fileExists(atPath: path as String))) 
        { 
            let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString 
            let path : NSString = documentsDirectory.appendingPathComponent("User.plist") as NSString 
            let data : NSMutableDictionary = NSMutableDictionary() 
            data.write(toFile: path as String, atomically: true) 
        } 
        let data : NSMutableDictionary = NSMutableDictionary(contentsOfFile: path as String)! 
        return data 
    }