Link 使用 Codable 时的 Realm 对象

Link Realm objects while using Codable

我想 link 部分到我的类别模型。我只在 JSON 响应中获取部分 ID,因此使用编码器我尝试这样做但没有成功

Solution below didn't work

public required convenience init(from decoder: Decoder) throws {
    self.init()
    let container = try decoder.container(keyedBy: CodingKeys.self)
    self.id = try container.decode(Int.self, forKey: .id)
    self.name = try container.decode(String.self, forKey: .name)
    self.color = try container.decodeIfPresent(String.self, forKey: .color) ?? ""
    let sectionId = try container.decode(Int.self, forKey: .section)
    let section = try! Realm().object(ofType: Section.self, forPrimaryKey: sectionId)
    self.section = section

}

My solution but I dont like the fact it will run a query everytime

final class Category : Object, Codable {

@objc dynamic var id: Int = 0
@objc dynamic var name: String = ""
@objc dynamic var color: String? = ""
@objc dynamic var sectionId: Int = 0
var section: Section? {
    return self.realm?.object(ofType: Section.self, forPrimaryKey: sectionId)
}

我相信一定有更好的方法。任何线索表示赞赏。

如果您对 属性 部分使用惰性变量,查询只会 运行 一次。不利的一面是,如果您正在观察 Category 对象的更改,如果相应的 Section 对象发生更改,您将不会收到通知。

class Category: Object {
    // ...
    @objc dynamic var sectionId: Int = 0

    lazy var section: Section? = {
        return realm?.object(ofType: Section.self, forPrimaryKey: sectionId)
    }()

    override static func ignoredProperties() -> [String] {
        return ["section"]
    }
}