Ash*_*lls 7 nscoding swift swift4 codable
我有以下结构......
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)
}
}
Run Code Online (Sandbox Code Playgroud)
编码Photo失败...
可选不符合Encodable,因为UIImage不符合Encodable
解码失败了......
期待非可选类型时找不到键可选择编码键\"image \""))
有没有一种方法来编码斯威夫特对象包括NSObject符合子类的属性NSCoding(UIImage,UIColor,等)?
感谢@vadian指点我编码/解码的方向Data......
class Photo: Codable {
let hasShadow: Bool
let image: UIImage?
enum CodingKeys: String, CodingKey {
case hasShadow, imageData
}
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2307 次 |
| 最近记录: |