【问题标题】:RLMException when save an object in a background thread在后台线程中保存对象时出现 RLMException
【发布时间】:2017-01-27 23:24:28
【问题描述】:

在后台异步保存对象时,我得到 RLMException: 'Can not add objects from a different Realm'。但是,如果删除异步代码,相同的保存工作正常。

此对象与现有对象有关系。例如:

class Person: Object {
  name: String
  school: School
}

class School: Object {
  name: String
}

let person = new Person()
person.name = "John"
person.school = school // Existing object selected from a dropdown.

DispatchQueue.global().async {
    do {
        let realm = try Realm!

        try realm.write {
            realm.add(person, update: true)
        }

        DispatchQueue.main.async {
            // Success!
        }
    } catch let error as NSError {
        DispatchQueue.main.async {
            // Error!
        }
    }
}

此代码会导致崩溃。但是,如果我删除 DispatchQueye.global().async,一切正常。我遇到了一些线程问题吗?

注意:school 对象是预先存在的,并且是从 Results<School> 集合中选择的。

【问题讨论】:

    标签: swift realm realm-mobile-platform


    【解决方案1】:

    Realm Object 实例一旦保存到 Realm 就不能在线程之间移动。由于school 将是在主线程上实例化的对象,因此您通过将其附加到非持久对象并将该批次移动到后台线程来创建冲突。

    要解决此问题,您需要使用 Realm's thread reference feature 制作 school 对象的后台版本。

    此外,除非您有特定原因在主线程上创建 Person,否则我还建议您也将其创建移至后台线程。

    let schoolRef = ThreadSafeReference(to: school)
    
    DispatchQueue.global().async {
        do {
            let realm = try Realm!
    
            let person = new Person()
            person.name = "John"
            person.school = realm.resolve(schoolRef)!
    
            try realm.write {
                realm.add(person, update: true)
            }
    
            DispatchQueue.main.async {
                // Success!
            }
        } catch let error as NSError {
            DispatchQueue.main.async {
                // Error!
            }
        }
    }
    

    【讨论】:

    • 感谢您为我指明正确的方向。正如您所指出的,我犯的错误之一是在主线程上创建 Person 。干杯!
    • 别担心!很高兴我能帮上忙! :)
    • 我觉得 Realm 可以提供更好的文档。
    • 我很确定我列出的所有信息现在都在 Realm 文档中。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 2018-09-02
    相关资源
    最近更新 更多