RealmSwift LinkingObjects 和 Decodable

MHC*_*Csk 0 realm swift realm-mobile-platform

我有一个 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
    }
}
Run Code Online (Sandbox Code Playgroud)

非常感谢 Chris Shaw 帮助我解决了这个问题。我写了一篇更深入的文章如何设置 Decodable 和 LinkingObjects,请参阅此处

小智 5

好吧,除非我遗漏了一些东西,否则这些LinkingObjects属性不需要包含在解码中。

我的假设是您从某个在线源接收 JSON,其中 a 的 JSON 由Product{ id: "", name: "" } 组成。只要您使用PortfolioItem关联正确创建Product,那么生成的LinkingObjects属性就是领域内动态查询的结果(因此无需任何 JSON 源即可工作)。

我今天无法测试编译答案,但您应该能够使用 CodingKeys 来简单地排除该属性,即通过将其添加到Product:-

private enum CodingKeys: String, CodingKey {
    case id
    case name
}
Run Code Online (Sandbox Code Playgroud)

另外,不相关,但请注意,您的convenience init函数不会初始化您传入的所有属性。