多线程核心数据 - persistentStoreCoordinator 与 parentContext
Multithreaded Core Data - persistentStoreCoordinator vs parentContext
我正在尝试解决因从多个线程访问同一个 NSManagedObjectContext
而导致的问题。我在 Apple docs 中找到以下内容:
let moc = … //Our primary context on the main queue
let privateMOC = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateMOC.parentContext = moc
privateMOC.performBlock {
//...
}
这似乎是我所追求的。我还在 tutorial 中发现了一些非常相似的东西,它已更新为 iOS 9:
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.persistentStoreCoordinator = coreDataStack.context.persistentStoreCoordinator
privateContext.performBlock { () -> Void in
//...
}
他们似乎都达到了相同的目的,但是 Apple 文档的版本使用 parentContext
而不是直接使用 persistantStoreCoordinator
。这两种方法有什么区别?
使用parentContext
。自 iOS 5.
以来,这优于使用持久存储协调器的方法
Prior to OS X v10.7 and iOS v5.0, the parent store is always a persistent store coordinator. In OS X v10.7 and later and iOS v5.0 and later, the parent store may be another managed object context. Ultimately the root of a context’s ancestry must be a persistent store coordinator. The coordinator provides the managed object model and dispatches requests to the various persistent stores containing the data.
在您的具体情况下:
If a context’s parent store is another managed object context, fetch and save operations are mediated by the parent context instead of a coordinator. This pattern has a number of usage scenarios, including:
- Performing background operations on a second thread or queue.
来源:NSManagedObjectContext class 参考,“Parent Store”。
我正在尝试解决因从多个线程访问同一个 NSManagedObjectContext
而导致的问题。我在 Apple docs 中找到以下内容:
let moc = … //Our primary context on the main queue
let privateMOC = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateMOC.parentContext = moc
privateMOC.performBlock {
//...
}
这似乎是我所追求的。我还在 tutorial 中发现了一些非常相似的东西,它已更新为 iOS 9:
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.persistentStoreCoordinator = coreDataStack.context.persistentStoreCoordinator
privateContext.performBlock { () -> Void in
//...
}
他们似乎都达到了相同的目的,但是 Apple 文档的版本使用 parentContext
而不是直接使用 persistantStoreCoordinator
。这两种方法有什么区别?
使用parentContext
。自 iOS 5.
Prior to OS X v10.7 and iOS v5.0, the parent store is always a persistent store coordinator. In OS X v10.7 and later and iOS v5.0 and later, the parent store may be another managed object context. Ultimately the root of a context’s ancestry must be a persistent store coordinator. The coordinator provides the managed object model and dispatches requests to the various persistent stores containing the data.
在您的具体情况下:
If a context’s parent store is another managed object context, fetch and save operations are mediated by the parent context instead of a coordinator. This pattern has a number of usage scenarios, including:
- Performing background operations on a second thread or queue.
来源:NSManagedObjectContext class 参考,“Parent Store”。