从不正确的线程访问领域

从不正确的线程访问领域

本文介绍了从不正确的线程访问领域 - Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 UITableViewController 的顶部是以下内容:

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()
        }
    }
 }

然后我收到错误

我该如何解决这个问题?

How could I fix this?

推荐答案

似乎写入发生在与最初访问对象不同的线程上。你应该能够通过传递 task 的id来修复它,并在你执行写操作之前使用它来从数据库中获取它(在异步块内)。

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).

所以在顶部:

var taskId = 0  // Set this accordingly

然后像

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()
        }
    }
 }

这篇关于从不正确的线程访问领域 - Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:57