gpt4 book ai didi

ios - swift 4 : Adding dictionaries to Plist

转载 作者:搜寻专家 更新时间:2023-11-01 05:47:20 25 4
gpt4 key购买 nike

所以,我有一个空的 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

最佳答案

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

关于ios - swift 4 : Adding dictionaries to Plist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47419327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com