Search code examples
swift3realm

Realm accessed from incorrect thread on next App run


So we have an app were the user needs to login. During the login data were downloaded from the internet and created into the Realm database.

If the app were closed and reopened we want the app to retain the user that has been logged-in so they don't need to relogin again. Everything is fine and ok during the first user login. When the app were closed and reopen the Realm database throws an error "Accessed from incorrect thread"...

I can't provide much of the code as I don't know where the issue is. I would like to know if rerunning the app again is it on different thread than before? and if it's then the how data created from previous thread can be accessed in the new thread without encountering the said error?

Any help will be appreciated... Thanks in advance


Solution

  • As you have encountered, you can't access a realm from a different thread than the thread it was opened. It is possible however to open multiple instances of the same realm on different threads (or the same thread if that's needed). Opening a realm is not an expensive operation, so there's not a performance issue in opening realms.

    I'm guessing in your case that you're downloading the data on a background thread. I'm also guessing the realm is first opened in the callback to that network request. That means the realm is opened on the thread that callback is on. If you try to access that realm on the main thread when reopening the app (or any other thread that's not the same thread as before) you'll get an error.

    Best practice is to open a new realm every time you know your doing work on a different thread. As I mentioned, this is not an expensive operation and should be used liberally.

    If you have some sort of RealmService or RealmManager as a singleton, I'd recommend against it. If the realm is initialised on the main thread, you won't be able to add records to it from a background thread.

    In short: whenever you are doing operations on a realm in a callback, unless you are 100% certain you are going to be on the same thread as you opened a realm on, create a new realm instance and use that to do your operatations.