我希望能够将 [String:Codable] 类型的字典保存到 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)")
}
}
但是我在解码功能中遇到了构建错误:
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')}
我想知道我们如何将 Codable 对象写入 plist 并恢复回来?