swift - 使用 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"]
}
}
推荐阅读
- wordpress - 如何从 wordpress 的屏幕选项中调用标题属性启用?
- apache-spark - 动态定义结构的列值
- sql - 如何为 SQL Server 编写连接查询?
- c# - 在 DevExpress GridView 上增加 RowHeight 的最佳方法?
- mysql - SQL查询找出显示员工姓名以及他们的年龄和经验年数
- html - 如何创建与图像颜色相匹配的透明渐变?
- java - 通过单击通知停止 AlarmManager
- android - 使用替换功能更新 SQLiteDatabase
- ruby - 如何使用 appium ruby 初始化隐藏页面对象
- c++ - 难以理解 C++ 中的链表中的一些作业