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

我相信一定有更好的方法。任何线索都很感激。

如果对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"]
}
}

最新更新