我对在后台队列上运行 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*/
}
最佳答案
因为perform和performAndWait是线程安全的。
假设您有两个上下文。
let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
let mainContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
通过使用perform或performAndWait,您可以保证它们在创建的队列中执行。否则,您将遇到并发问题。
所以你可以得到下面的行为。
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
}
}
要了解有关并发的更多信息,这里有 link Apple 文档。
关于swift - 为什么我应该使用 NSManagedObjectContext 的 Perform() 和 PerformAndWait() 而我可以使用 DispatchQueue.global,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56807900/