领域 Swift 主键无法检索到正确的值
Realm Swift primary key would not retrieve the correct value
我正在尝试检索我的领域数据库中给定对象的属性。除了始终具有默认值的主键外,每个 属性 都正确显示。
例如:
A.swift
@objcMembers class A: Object, Codable{
var id: Int64 = 0
dynamic var otherProperty: String?
private enum CodingKeys: String, CodingKey {
case id
case otherProperty
}
override static func primaryKey() -> String{
return "id"
}
}
假设我们有 class A,如上例所示。当我将 A 对象添加到 Realm 数据库中时,使用给定的 id=10 和 otherProperty="other property",它已正确保存.我什至可以用 Realm Browser 看到它。
现在,我正在尝试使用以下代码:
let realm = try! Realm()
let aObj = realm.objects(A.self).first
print(aObj!.id) //printing 0
print(aObj!.otherProperty) //printing "other property"
显然,这里的问题是我没有在 aObj 中收到 id=10 的值,因为我会期待。
我试过调试它看看问题出在哪里,最奇怪的事情发生在那里。 po aObj
会正确打印我的对象:
Optional<A>
some: A{
id = 10;
otherProperty="other property"
}
但是,如果我尝试只打印出 id,那么如果我 运行 po aObj!.id
命令,我会得到以下结果:
Optional<Int64>
- some : 0
使您的 ID 动态化
dynamic var id: Int64 = 0
realm.add(A(value: ["id": 10, "otherProperty": "otherProperty"]) , update: true)
print("aObj?.id") //printing 10
我正在尝试检索我的领域数据库中给定对象的属性。除了始终具有默认值的主键外,每个 属性 都正确显示。
例如:
A.swift
@objcMembers class A: Object, Codable{
var id: Int64 = 0
dynamic var otherProperty: String?
private enum CodingKeys: String, CodingKey {
case id
case otherProperty
}
override static func primaryKey() -> String{
return "id"
}
}
假设我们有 class A,如上例所示。当我将 A 对象添加到 Realm 数据库中时,使用给定的 id=10 和 otherProperty="other property",它已正确保存.我什至可以用 Realm Browser 看到它。
现在,我正在尝试使用以下代码:
let realm = try! Realm()
let aObj = realm.objects(A.self).first
print(aObj!.id) //printing 0
print(aObj!.otherProperty) //printing "other property"
显然,这里的问题是我没有在 aObj 中收到 id=10 的值,因为我会期待。
我试过调试它看看问题出在哪里,最奇怪的事情发生在那里。 po aObj
会正确打印我的对象:
Optional<A>
some: A{
id = 10;
otherProperty="other property"
}
但是,如果我尝试只打印出 id,那么如果我 运行 po aObj!.id
命令,我会得到以下结果:
Optional<Int64>
- some : 0
使您的 ID 动态化
dynamic var id: Int64 = 0
realm.add(A(value: ["id": 10, "otherProperty": "otherProperty"]) , update: true)
print("aObj?.id") //printing 10