I have been opening realm once then passing it between view controllers. At some point I’ve encountered error stating “realm accessed from incorrect thread”. After Googling I’ve found this stack thread which stated the following:
As such, best practice with Realm is to recreate your Realm objects on the same thread each time you want to perform a new operation on that thread. Realm internally caches instances of
Realmon a per-thread basis, so there’s very little overhead involved with calling
And so I’ve started to try to re-open realm using the same realmApp.currentUser?.id for the configuration. In my app user starts with anonymous credential login. If I then link the user to email/pass user, log out and try to log in again with email/pass (which opens the realm again with realmApp.currentUser?.id) I’m getting error stating that I cannot open realm due to it being “already opened with different sync user.” (even though user id is still the same) I was looking for a way to close realm during log out, but read in docs that “there is no need to close realm”.
TL;DR I’m trying to figure out what’s the best approach to using Realm. Should I re-open it in various places so I don’t risk access from different thread? Should I pass realm instance between view controllers? How do I avoid issues described above?