问题是列表类型不符合Codable,以下类无法插入Realm。
例如,
class Book: Codable { var name: String = "" var author: String = "" var tags = [String]() }
考虑到上述类符合Codable,如果将该类存储到Realm,则需要使用List<Object>type代替[String]
List<Object>
[String]
class Book: Object, Codable { @objc dynamic var name: String = "" @objc dynamic var author: String = "" var tags = List<Tag>() required convenience init(from decoder: Decoder) throws { self.init() let container = try decoder.container(keyedBy: CodingKeys.self) name = try container.decode(String.self, forKey: .name) author = try container.decode(String.self, forKey: .author) tags = try container.decode(List<Tag>.self, forKey: .tags) // this is problem. } } class Tag: Object, Codable { @objc dynamic var string: String = "" required convenience init(from decoder: Decoder) throws { self.init() let container = try decoder.container(keyedBy: CodingKeys.self) string = try container.decode(String.self, forKey: .string) } }
为了符合Codable,它应该是实现Decodable协议。(required convenience init(from decoder: Decoder) throws)
Decodable
required convenience init(from decoder: Decoder) throws
但是,List类型不符合Codable(Decodable),如果类具有List类型,则无法使用Codable 。
List
Codable
如何解决这个问题?
谢谢,
你快到了。在初始化程序内部,您可以使用解码后的数组初始化列表。基本上,改变
tags = try container.decode(List<Tag>.self, forKey: .tags) // this is problem.
至
let tagsArray = try container.decode([Tag].self, forKey: .tags) tags = List(tagsArray) // Now you are good
正如评论中指出的那样,List构造函数不再像这样工作
您现在想要:
tags.append(objectsIn: tagsArray)