Moh*_*sen 3 xcode core-data nsmanagedobjectcontext swift dispatch-queue
我对在后台队列上运行 CoreData 代码有一些困惑。
我们可以使用一些方法使用 NSManagedObjectContext 在后台线程上执行 CoreData 代码。
viewContext.perform { /*some code will run on the background thread*/ }
viewContext.performAndWait{ /*some code will run on the background thread*/ }
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么我应该使用这些函数而不是使用普通方式使用 DispatchQueue 在后台线程上运行一些代码
DispatchQueue.global(qos: .background).async {
/*some code will run on the background thread*/
}
Run Code Online (Sandbox Code Playgroud)
因为perform和performAndWait是线程安全的。
假设您有两个上下文。
let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
let mainContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
Run Code Online (Sandbox Code Playgroud)
通过使用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
}
}
}
Run Code Online (Sandbox Code Playgroud)
否则,它们都将在后台执行,如以下代码所示。
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
}
}
Run Code Online (Sandbox Code Playgroud)
要了解有关并发的更多信息,请参阅此处Apple 文档的链接。
| 归档时间: |
|
| 查看次数: |
1746 次 |
| 最近记录: |