我希望能够保存字符串类型的字典:可编码到plist并恢复为相同类型。我试过了,但它抛出了错误:
let dictionary:[String:Any] = ["point":CGPoint(1,1), "value": 10, "key" : "testKey"]
do {
let url = FileManager.default.temporaryDirectory.appendingPathComponent("test.plist")
try savePropertyList(dictionary, toURL: url)
buildFromPlist(url)
} catch {
print(error)
}
private func savePropertyList(_ plist: Any, toURL url:URL) throws
{
let plistData = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
try plistData.write(to: url)
}
private func buildFromPlist(_ url:URL)
{
do {
let data = try Data(contentsOf: url)
let decoder = PropertyListDecoder()
let dictionary = try decoder.decode([String:Decodable], from: data)
NSLog("\(dictionary)")
} catch {
NSLog("Error decoding \(error)")
}
}但是我在decode函数中得到了构建错误:
Value of protocol type 'Decodable' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols我想知道我如何读回我保存到plist文件中的字典?
编辑:即使savePropertyList在运行时失败,出现诸如CGPoint和CGAffineTransform这样的对象,也会出现以下错误-
"Property list invalid for format: 100 (property lists cannot contain objects of type 'CFType')" UserInfo={NSDebugDescription=Property list invalid for format: 100 (property lists cannot contain objects of type 'CFType')}我想知道我们如何编写可编码的对象来plist和恢复?
发布于 2020-09-28 18:25:01
这是行不通的,因为decoder.decode行中的类型必须是具体类型。而没有尾随.self的[String:Decodable]将抛出另一个错误。
Codable协议的目标是序列化自定义结构或类,因此使您的字典成为结构
struct MyType : Codable {
let point : CGPoint
let value : Int
let key : String
}并对此进行编码。在解码部分中写入
let item = try decoder.decode(MyType.self, from: data)https://stackoverflow.com/questions/64100207
复制相似问题