我想将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属性使用惰性变量,则查询将仅运行一次。不利的一面是,如果您观察到类别对象的更改,并且相应的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"]
}
}