Single object, multiple realm instances in swift


#1

Is it a problem if you 1) create realm instance 2) get an object from that instance 3) make changes to the object 4) create another realm instance 5) save object using the second realm instance (assuming this all happens in the same thread)?

Right now the design in my app depends on this pattern, and while I don’t see any crashes, I just want to make sure that I’m not violating any rules. Here’s a simplified version of what I’m doing. Notice that read() and update() create different instances of realm, that’s what I would like to verify.

func doIt() {
    if let dog = read(type: Dog.self, forPrimaryKey: "key") {
        makeChanges(to: dog)
        update(object: dog)
    }
}

func makeChanges(to dog: Dog) {
    // TODO: make some changes
}

func read<T: Object>(type: T.Type, forPrimaryKey primaryKey: String) -> T? {
    let realm = try! Realm()
    return realm.object(ofType: type, forPrimaryKey: primaryKey)
}

func update<T: Object>(object: T) {
    let realm = try! Realm()
    try! realm.write {
        realm.add(object, update: true)
    }
}

#2

If I remember right, the realm instances are shared on the same thread - so you use the same. I don’t know where I read it, or I just imagine things…