Realm object as a member is zero after saving

I ran into a problem when a Realm object has another Realm object as a member, which is always nil after being added to the database.

 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" } } 

A reference to the Medicine object is always added after adding.

 class Medicine: Object { var uuid = NSUUID().UUIDString var name: String? override static func primaryKey() -> String? { return "uuid" } } 

Object Creation

 let medPack = MedPack(medicine: med) 

Adding to the 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) } } 
+2
source share
1 answer

After comparing this code with one of the projects with Realm samples, it seems that just setting Object as a child of another also implicitly writes it to the database.

Instead, you may need to reorganize your code a bit, but make sure that you explicitly add your Medicine object to Realm in the write transaction before setting its relationship to MedPack , and then write MedPack to the database.

+3
source

Source: https://habr.com/ru/post/1243205/


All Articles