我有一个我需要可解码的Realm模型类,所以我可以从JSON序列化它并将其保存到数据库。每个PortfolioItem
都与一个Product
有关,在某些时候我需要通过反向关系从PortfolioItem
到达Product
。这就是为什么我有LinkingObjects
财产。问题是当我尝试遵守Decodable
协议时。编译器给我一个错误Cannot automatically synthesize 'Decodable' because 'LinkingObjects<PortfolioItem>' does not conform to 'Decodable'
。怎么处理这个?我发现在线LinkingObjects和Decodable很少,我不知道如何处理这个问题。
class PortfolioItem: Object {
@objc dynamic var id: String = ""
@objc dynamic var productId: String = ""
@objc dynamic public var product: Product?
convenience init(id: String, productId: String) {
self.init()
self.id = id
}
}
final class Product: Object, Decodable {
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
private let portfolioItems = LinkingObjects(fromType: PortfolioItem.self, property: "product")
public var portfolioItem: PortfolioItem? {
return portfolioItems.first
}
convenience init(id: String, name: String) {
self.init()
self.id = id
}
}
非常感谢Chris Shaw帮助我解决这个问题。我写了一篇更深入的文章,如何设置Decodable和LinkingObjects,look HERE。