Inconsistent state from Realm on a background thread in Swift

153 Views Asked by At

Despite using autoreleasepool and instantiating a new realm instance on each access of realm, I sometimes get inconsistent state.

In the following (contrived) example there is only one MyObject stored in the database. After the delete, the second query still sees the instance. Can anyone shed light on why this is happening? It works most of the time, but on rare occasions I get inconsistent state. Sometimes it happens when accessing realm on two separate threads, but it once happened even on the same thread.

I understand that I can probably just call realm.refresh() before the second query (I've not tested this), but my question is why do I need to? Each function has its own realm instance and is wrapped in autoreleasepool as per the docs recommendation. Am I misunderstanding something?

func start() {
    DispatchQueue.global().async {
        update1()
        update2()
    }
}

func update1() {
    autoreleasepool {
        let realm = try! Realm()
        let object = realm.objects(MyObject.self).first!  // expecting object here
        try! realm.write {
            realm.delete(object)
        }
    }
}

func update2() {
    autoreleasepool {
        let realm = try! Realm()
        if let object = realm.objects(MyObject.self).first {
            fatalError("not expecting object here")
        }
    }
}

Thanks in advance!

0

There are 0 best solutions below