我有以下結構...夫特可編碼協議...編碼/解碼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的確實 不符合可編碼
解碼失敗...
鑰匙未發現期待非可選類型可選時 編碼鍵\「圖像\」「))
有沒有辦法來編碼斯威夫特對象包括符合NSCoding
NSObject
子類的屬性(UIImage
,UIColor
等)?
你必須編寫自定義編碼/解碼碼存檔/解除存檔的對象,並從'Data'。請參閱[編碼和解碼定義類型(https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) – vadian