Realm accessed from incorrect thread - Swift 3

前端 未结 4 916
借酒劲吻你
借酒劲吻你 2021-01-06 04:37

At the top of my UITableViewController is the following:

let queue = DispatchQueue(label: \"background\")

When a task is dele

4条回答
  •  迷失自我
    2021-01-06 05:21

    You could also use a ThreadSafe reference, a specific way to pass realm objects between threads:

    let realm = try! Realm()
    let person = Person(name: "Jane") // no primary key required 
    try! realm.write {
        realm.add(person)
    }
    let personRef = ThreadSafeReference(to: person)
    DispatchQueue(label: "com.example.myApp.bg").async {
        let realm = try! Realm()
        guard let person = realm.resolve(personRef) else {
        return // person was deleted
    }
    try! realm.write {
        person.name = "Jane Doe"
    }
    

    The steps provided by Realm Documentation:

    1. Initialize a ThreadSafeReference with the thread-confined object.
    2. Pass that ThreadSafeReference to a destination thread or queue.
    3. Resolve this reference on the target Realm by calling Realm.resolve(_:).
    4. Use the returned object as you normally would.

提交回复
热议问题