[英]Realm object as member is nil after saving
I'm facing an issue where a Realm object has another Realm object as member which is always nil
after adding to the database. 我面临一个问题,其中Realm对象将另一个Realm对象作为成员,添加到数据库后始终为
nil
。
class MedPack: Object {
dynamic var uuid = NSUUID().UUIDString
dynamic var medicine: Medicine?
convenience init(medicine: Medicine) {
self.init()
self.medicine = medicine
}
override static func primaryKey() -> String? {
return "uuid"
}
}
The reference to the object Medicine
is always nil after adding. 添加后,对对象
Medicine
的引用始终为nil。
class Medicine: Object {
var uuid = NSUUID().UUIDString
var name: String?
override static func primaryKey() -> String? {
return "uuid"
}
}
Creation of object 创建对象
let medPack = MedPack(medicine: med)
Adding to database 添加到数据库
static let sharedInstance = DBHelper()
var realmDb: Realm!
private init() {
realmDb = try! Realm()
}
func store(object: Object) {
try! self.realmDb.write {
self.realmDb.add(object)
}
}
After comparing this code to one of the Realm sample projects, it would appear that simply setting an Object
as a child of another does not implicitly write it to the database as well. 在将该代码与Realm示例项目之一进行比较之后,似乎将
Object
设置为另一个子Object
并不会隐式地将其写入数据库。
Instead, you may need to refactor your code slightly, but make sure you explicitly add your Medicine
object to Realm in a write transaction, before you set its relation to MedPack
and then write MedPack
to the database. 相反,您可能需要稍微重构代码,但在将对象设置为与
MedPack
关系,然后再将MedPack
写入数据库之前,请确保在写事务中将Medicine
对象显式添加到Realm中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.