夫特可编码协议...编码/解码NSCoding类

夫特可编码协议...编码/解码NSCoding类

问题描述:

我有以下结构...夫特可编码协议...编码/解码NSCoding类

struct Photo: Codable { 

    let hasShadow: Bool 
    let image: UIImage? 

    enum CodingKeys: String, CodingKey { 
     case `self`, hasShadow, image 
    } 

    init(hasShadow: Bool, image: UIImage?) { 
     self.hasShadow = hasShadow 
     self.image = image 
    } 

    init(from decoder: Decoder) throws { 
     let container = try decoder.container(keyedBy: CodingKeys.self) 
     hasShadow = try container.decode(Bool.self, forKey: .hasShadow) 

     // This fails 
     image = try container.decode(UIImage?.self, forKey: .image) 
    } 

    func encode(to encoder: Encoder) throws { 
     var container = encoder.container(keyedBy: CodingKeys.self) 
     try container.encode(hasShadow, forKey: .hasShadow) 

     // This also fails 
     try container.encode(image, forKey: .image) 
    } 
} 

编码一个Photo失败,...

可选不符合可编码因为UIImage的确实 不符合可编码

解码失败...

钥匙未发现期待非可选类型可选时 编码键\“图像\”“))

有没有办法来编码斯威夫特对象包括符合NSCodingNSObject子类的属性(UIImageUIColor等)?

+3

你必须编写自定义编码/解码码存档/解除存档的对象,并从'Data'。请参阅[编码和解码定义类型(https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) – vadian

由于@vadian指着我的编码/解码Data的方向......

class Photo: Codable { 

    let hasShadow: Bool 
    let image: UIImage? 

    enum CodingKeys: String, CodingKey { 
     case `self`, hasShadow, imageData 
    } 

    init(hasShadow: Bool, image: UIImage?) { 
     self.hasShadow = hasShadow 
     self.image = image 
    } 

    required init(from decoder: Decoder) throws { 
     let container = try decoder.container(keyedBy: CodingKeys.self) 
     hasShadow = try container.decode(Bool.self, forKey: .hasShadow) 

     if let imageData = try container.decodeIfPresent(Data.self, forKey: .imageData) { 
      image = NSKeyedUnarchiver.unarchiveObject(with: imageData) as? UIImage 
     } else { 
      image = nil 
     } 
    } 

    func encode(to encoder: Encoder) throws { 
     var container = encoder.container(keyedBy: CodingKeys.self) 
     try container.encode(hasShadow, forKey: .hasShadow) 

     if let image = image { 
      let imageData = NSKeyedArchiver.archivedData(withRootObject: image) 
      try container.encode(imageData, forKey: .imageData) 
     } 
    } 
} 
+1

那么到底'Codable'并没有真正做任何事情变得更容易,使用“自定义类型”时, ? : - | – d4Rk

+0

好 - 它可以让你编码/解码非'NSObject'子类(枚举和结构) –

+0

@AshleyMills,我得到这个错误“类型‘照片’不符合协议‘可解’”,而在复制这段代码我文件。 –