从不同的线程到达 Realm Results 对象会导致崩溃

Reaching Realm Results object from different thread gives crash

我的 viewModel 中有一个 Results 对象定义和初始化如下

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

在另一个函数中(在 self.followers 初始化和实现之后)我尝试在不同的线程中获取以下对象,但出现以下崩溃。

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: 如果我用 realm.objects(T.self) 得到我的对象 它不会崩溃。

P.S 2: 我发现过滤导致崩溃。如果我删除过滤,它可以工作,但我需要过滤。我尝试使用 Array(followers).filter 将其分配给非实时数组,但也不起作用。

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

所以您有 2 个主要选项,如果您要使用任何数据来填充 UI,则必须在主线程中获取对象。

另一种选择是创建一个新的 Realm 实例并在主线程中再次获取结果,创建一个 Realm 应该是非常轻量级的。

您也可以在线程之间传递对象,但这更复杂。