Swift 4:向 Plist 添加字典 [英] Swift 4: Adding dictionaries to Plist

查看:21
本文介绍了Swift 4:向 Plist 添加字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, i have an empty plist, i am trying to create these values in the 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 中

everything is fine here, but the question is, when i click the plist in my xcode project, its empty, these values are only printed not inserted to the plist

推荐答案

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

NSKeyedUnarchiver is the wrong way to save property lists.

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

There is a dedicated struct PropertyListSerialization to load and save property lists.

首先声明一个计算属性plistURL

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

以及两种加载和保存的方法

and two methods for loading and saving

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 [:]
    }
    return plist
}

创建字典并保存

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

要更新值读取它,更新值并将其保存回来

To update a value read it, update the value and save it back

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

这篇关于Swift 4:向 Plist 添加字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆