3

我对在后台队列上运行 CoreData 代码有些困惑。

我们可以使用一些方法来使用 NSManagedObjectContext 在后台线程上执行 CoreData 代码。

viewContext.perform { /*some code will run on the background thread*/ }
viewContext.performAndWait{ /*some code will run on the background thread*/ }

我在这里的问题是为什么我应该使用这些函数而不是使用普通方式使用 DispatchQueue 在后台线程上运行一些代码

DispatchQueue.global(qos: .background).async { 
     /*some code will run on the background thread*/ 
}
4

1 回答 1

3

因为performperformAndWait是线程安全的。

假设您有两个上下文。

let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
let mainContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

通过使用performperformAndWait,您可以保证它们在创建的队列中执行。否则,您将遇到并发问题。

所以你可以得到下面的行为。

DispatchQueue.global(qos: .background).async {
        //some code will run on the background thread
        privateContext.perform {
            //some code will run on the private queue
            mainContext.perform {
                //some code will run on the main queue
            }
        }
    }

否则,它们将全部在后台执行,如以下代码所示。

DispatchQueue.global(qos: .background).async {
        //some code will run on the background thread
            do {
                //some code will run on the background thread
                try privateContext.save()
                do {
                    //some code will run on the background thread
                    try mainContext.save()
                } catch {
                    return
                }
            } catch {
                return
            }
        }

要了解更多关于并发的信息,这里有一个指向Apple 文档的链接。

于 2019-07-07T18:00:22.167 回答