ios - Realm 不正确的线程访问崩溃

标签 ios multithreading asynchronous realm

我参加这个聚会迟到了,而Realm还是新手

我创建了一个signleton类,该类具有以下编写方法,但是由于不正确的线程访问,它有时会崩溃

让我知道我在这里做错了。

 func save<T:Object>(_ realmObject:T) {
    let backgroundQueue = DispatchQueue(label: ".realm", qos: .background)
    backgroundQueue.async {
        let realm = try! Realm()
       try! realm.write {
            realm.add(realmObject)

        }
    }

}

最佳答案

感谢您提出这个问题!错误的线程访问异常是由于Realm对象通过线程边界传递的结果。我建议阅读有关Passing Instances Across Threadsthis blog post的文档(特别是有关线程限制的部分)。

为了避免该异常,您需要将代码更改为:

func save<T:Object>(_ realmObject:T) {
    let realmObjectRef = ThreadSafeReference(to: realmObject)
    let backgroundQueue = DispatchQueue(label: ".realm", qos: .background)
    backgroundQueue.async {
        guard let realmObject = realm.resolve(realmObjectRef) else {
            return // although proper error handling should happen
        }

        let realm = try! Realm()
        try! realm.write {
            realm.add(realmObject)
        }
    }
}
ThreadSafeReference对象documented here为您提供了给定Realm对象的线程安全引用,该引用可以通过线程边界传递,一旦您安全地位于其他线程中,便可以解析回线程受限对象。希望对您有所帮助,让我知道您是否还有其他需要。干杯!

关于ios - Realm 不正确的线程访问崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42002733/

相关文章:

python - Google App Engine 后台线程与任务

python - Celery 可以将状态更新传递给非阻塞调用者吗?

ios - 如何使用 Swift 语言创建 Cocoa Touch Framework 并在其他 Swift 项目中使用它?

ios - OpenCV 3.0 CascadeClassifier.load()断言失败(!empty)

ios - MKMapSnapshotOptions : Adding snapshot of Custom Pin Annotation View or UIView

java - 多线程共享变量

ios - 应用程序将不再编译

java - 在 Java 中总是忽略调用 Thread sleep() 的 InterruptedException 是否安全

javascript - 为什么 async-await 一起运行时比 promises 慢得多