0

我希望能够将 [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 并恢复回来?

4

1 回答 1

1

这不起作用,因为该decoder.decode行中的类型必须是具体类型。并且[String:Decodable]没有尾随.self将引发另一个错误。

Codable协议的目标是序列化自定义结构或类,以便使您的字典成为结构

struct MyType : Codable {
    let point : CGPoint
    let value : Int
    let key : String
}

并对其进行编码。在解码部分写

let item = try decoder.decode(MyType.self, from: data)
于 2020-09-28T10:25:01.090 回答