You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Realm Swift异步写入代码报错:两种写法为何结果不同?

Realm异步写入代码一处报错的原因

我是Swift并发(尤其是Realm Swift)的新手,有两段自认为逻辑一致的示例代码,但其中一段无法正常运行。

无法运行的代码

var localRealm: Realm {
    get {
        return try! Realm()
    }
}
fileprivate func testAsyncRealm() {
    self.localRealm.beginAsyncWrite {
        self.localRealm.create(SwiftStringObject.self, value: ["string2"])
        self.localRealm.commitAsyncWrite(allowGrouping: true) { error in
            print(error)
        }
    }
}

抛出的异常

Terminating app due to uncaught exception 'RLMException', reason: Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.

正常运行的代码

fileprivate func testAsyncRealm() {
    let realm = try! Realm()
    realm.beginAsyncWrite {
        realm.create(SwiftStringObject.self, value: ["string2"])
        realm.commitAsyncWrite(allowGrouping: true) { error in
            print(error)
        }
    }
}

问题原因

核心问题出在localRealm这个计算属性上:

  • 每次访问self.localRealm,都会触发getter创建一个全新的Realm实例
  • 调用self.localRealm.beginAsyncWrite时,是在实例A上开启了异步写入事务,但紧接着调用self.localRealm.create时,生成了完全无关的实例B——这个实例没有开启任何事务,自然会触发报错
  • 最后调用self.localRealm.commitAsyncWrite时,又生成了实例C,同样和最初开启事务的实例A无关联,根本无法提交事务

而正常运行的代码中,let realm = try! Realm()只创建了一个Realm实例,后续所有操作都在同一个实例上完成,符合Realm异步写入的要求,因此能正常执行。

Realm版本:10.40.0

内容的提问来源于stack exchange,提问作者Foster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:32:22