首页 > 解决方案 > 使用 Codable 时链接 Realm 对象

问题描述

我想将 Section 链接到我的 Category 模型。我只在 JSON 响应中获取部分 id,所以使用编码器我尝试这样做但没有用

下面的解决方案不起作用

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

}

我的解决方案,但我不喜欢它每次都会运行查询的事实

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)
}

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

标签: swiftrealmcodable

解决方案


如果您对 section 属性使用惰性变量,则查询将只运行一次。不利的一面是,如果您正在观察 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"]
    }
}

推荐阅读