1

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!

vin047
  • 260
  • 3
  • 12
  • Really clear question and nicely laid out. However, I copy and pasted your code within a loop that ran 1000 times. It worked 1000 out of 1000 times correctly; update2 never read the MyObject that was deleted in update1. Either I was 'lucky' or it suggests there is some other code influencing Realm or MyObject. – Jay Dec 09 '19 at 17:25
  • Thanks for the compliment :) I figured it **should** work, so I'm not really sure what's going on. The ```MyObject``` object has two child realm-objects. As Realm does not support cascading delete, I've implemented it myself, so the child objects are deleted first, then the parent. But on query, the children remain deleted but the parent object is still present?! – vin047 Dec 09 '19 at 18:46
  • It may be helpful to include your actual Realm model(s) and then the actual code you're using to delete them. Scale down those models as much as possible to make it a MCVE - [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Jay Dec 09 '19 at 18:50

0 Answers0