Plist编码和解码回字典[String:Decodable]

问题描述

我希望能够将[String:Codable]类型的Dictionary保存到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并恢复回来?

解决方法

这行不通,因为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)