realm.write 是异步的吗

Is realm.write asynchronous

我正在尝试将 CustomUserData 添加到我的 MongoDB 领域数据库,然后刷新用户数据。

但看起来 realm.write 是异步的,而我认为它是同步的 (Swift Realm Write method is Sync or Async Thread)。所以我的问题是到底是什么情况,什么时候是同步的,为什么 .refreshCustomData() 函数只能在短暂的延迟后获取新数据。

try! realm.write {
   realm.add(member)
}

app.currentUser!.refreshCustomData()
// -> after the refresh the customUserData is still empty
// only if you call it with a short delay the result contains the new written data

不,它不是异步的。 查看实现(删除所有不重要的理解)。 如果没有发生异常,写入事务将简单地启动并提交,否则事务将回滚。

public func write<Result>(_ block: (() throws -> Result)) throws -> Result {
    beginWrite()
    var ret: Result!
    do {
        ret = try block()
    } catch let error {
        if isInWriteTransaction { cancelWrite() }
        throw error
    }
    if isInWriteTransaction { try commitWrite(withoutNotifying: tokens) }
    return ret
}

但是:如果在另一个线程中查询刚刚写入的数据,那就是另外一回事了。 新对象在一段时间内不会在另一个线程上可见。

我的解决方案是:在同一个线程上进行读写操作。

另请参阅: