CoreData:backgroundContext 和具有 privateQueueConcurrencyType 的子上下文之间的区别?

ane*_*yzm 5 core-data nsmanagedobjectcontext ios swift

使用 CoreData,您可以要求容器使用container.newBackgroundContext().

这对于在后台使用核心数据而不影响 UI 主上下文非常有用。

您还可以使用以下命令创建子上下文privateQueueConcurrencyType

let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如果我没有错的话,上下文仍将在不同队列的后台执行。

那么两者之间有什么区别以及何时使用其中一种和另一种呢?

J. *_*Doe 4

您对上下文的初始化,即:

let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
Run Code Online (Sandbox Code Playgroud)

在引入NSPersistentContainer之前被广泛使用。另请参阅https://developer.apple.com/documentation/coredata/using_core_data_in_the_background,其中指出:

初始化和配置上下文对于这两种上下文,NSManagedObjectContext 实例的初始化是相同的: let moc = NSManagedObjectContext(concurrencyType:<#type#>) 作为初始化的一部分传入的参数确定返回的 NSManagedObjectContext 类型。当您使用 NSPercientContainer 时,您将 viewContext 属性配置为主队列 (NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType) 上下文,并将与 PerformBackgroundTask(_:) 和 newBackgroundContext()关联的上下文配置为私有队列 (NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)。

newBackgroundContext()的文档说明如下:

调用此方法会导致持久容器创建并返回一个新的 NSManagedObjectContext,并将 concurrencyType 设置为 NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType。 这个新上下文将直接与 NSPersistentStoreCoordinator 关联,并设置为自动使用 NSManagedObjectContextDidSave 广播。

newBackgroundContext()与您提供的代码执行相同的操作,以及我在上面的引用中突出显示的额外内容。

在针对 iOS 10+ 进行开发时,我建议当您想要阻止调用线程时使用NSPersistentContainer和 use ,或者当您想要将工作分派到后台时不想调用线程来阻止。newBackgroundContext()performBackgroundTask

我在 iOS 10 之前没有使用过 CoreData,但我认为在仅使用concurrenyType. 有了 就不再需要了newBackgroundContext()