Ad

Realm Object As Member Is Nil After Saving

- 1 answer

I'm facing an issue where a Realm object has another Realm object as member which is always nil after adding 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"
    }
}

The reference to the object Medicine is always nil after adding.

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)
    }
}
Ad

Answer

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.

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.

Ad
source: stackoverflow.com
Ad