Search code examples
iosswiftrealm

Reaching Realm Results object from different thread gives crash


I have a Results object in my viewModel defined and initialized as below

private var followings: Results<Following>!
// This runs in main thread
self.followers = try RealmHelper.getObjects(t: Follower.self)

In another function (after self.followers initialized and fulfilled) I try to get this followings object in different thread but gives bellow crash.

Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.'

DispatchQueue.global(qos: .userInitiated).async { 
  let currentFollowersIds = self.followers.filter("friendShip.isFollowingYou == true")
}

P.S: If I get my objects with realm.objects(T.self) It doesn't give crash.

P.S 2: I found that filtering gives the crash. If I remove filtering, It works but I need filtering. I tried assigning it to not-live array with Array(followers).filter but doesn't work also.


Solution

  • Realm objects can only be used from the same thread that they were fetched.

    So you have 2 main options, if you are going to use any of your data to populate UI, you'll have to fetch the objects in the main thread.

    The other option is to create a new Realm instance and fetch the results again in the main thread, creating a Realm is supposed to be really lightweight.

    You can also pass objects between threads but that is more complicated.