Search code examples
iosswiftmultithreadingrealmgrand-central-dispatch

Realm accessed from incorrect thread - Swift 3


At the top of my UITableViewController is the following:

let queue = DispatchQueue(label: "background")

When a task is deleted, the following executes:

self.queue.async {
    autoreleasepool {
        let realm = try! Realm()
        realm.beginWrite()
        realm.delete(task)
        do {
            try realm.commitWrite()
        } catch let error {
            self.presentError()
        }
    } 
 }

And then I receive the error

terminating with uncaught exception of type realm::IncorrectThreadException: Realm accessed from incorrect thread.

How could I fix this?


Solution

  • It seems like the write is happening on a different thread than the object was originally accessed from. You should be able to fix it by passing task's id and using that to fetch it from the database right before you do the write (inside the async block).

    So at the top:

    var taskId = 0  // Set this accordingly
    

    and then something like

    self.queue.async {
        autoreleasepool {
            let realm = try! Realm()
            let tempTask = // get task from Realm based on taskId
            realm.beginWrite()
            realm.delete(tempTask)
            do {
                try realm.commitWrite()
            } catch let error {
                self.presentError()
            }
        } 
     }