Plist编码和解码回字典[String:Decodable] [英] Plist encoding and decoding back to Dictionary [String:Decodable]
问题描述
我希望能够将[String:Codable]类型的Dictionary保存到plist并恢复原样。我试过了,但是会引发错误:
I want to be able to save Dictionary of type [String:Codable] to plist and recover back as same. I tried this but it throws errors:
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)")
}
}
但是我在解码功能中遇到了构建错误:
But I get build errors in decode function:
Value of protocol type 'Decodable' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols
我不知道如何读回保存到plist文件的字典?
I wonder how I read back the dictionary I saved to plist file?
编辑:即使savePropertyList在运行时也由于诸如CGPoint和CGAffineTransform之类的对象而失败,并显示错误-
Even savePropertyList fails at runtime with objects such as CGPoint and CGAffineTransform with the error -
"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')}
我想知道我们如何才能将Codable对象写入plist并恢复回来?
I wonder how can we write Codable objects to plist and recover back?
推荐答案
这是行不通的,因为 decoder.decode
行必须是具体类型。而 [String:Decodable]
而不尾随 .self
会引发另一个错误。
This cannot work because the type in the decoder.decode
line must be a concrete type. And [String:Decodable]
without trailing .self
will throw another error.
Codable
协议的目标是序列化自定义结构或类,从而使字典成为结构
The goal of the Codable
protocol is to serialize custom structs or classes so make your dictionary a struct
struct MyType : Codable {
let point : CGPoint
let value : Int
let key : String
}
并将其编码。在解码部分中写
and encode this. In the decoding part write
let item = try decoder.decode(MyType.self, from: data)
这篇关于Plist编码和解码回字典[String:Decodable]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!