Reputation: 2726
I'm trying to resolve issues that are being caused by accessing the same NSManagedObjectContext
from multiple threads. I found the following in the Apple docs:
let moc = … //Our primary context on the main queue
let privateMOC = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateMOC.parentContext = moc
privateMOC.performBlock {
//...
}
Which seems to be what I'm after. I also found something very similar in a tutorial which has been updated for iOS 9:
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.persistentStoreCoordinator = coreDataStack.context.persistentStoreCoordinator
privateContext.performBlock { () -> Void in
//...
}
They both seem to achieve the same, however the Apple doc's version uses parentContext
instead of using the persistantStoreCoordinator
directly. What is the difference between these two approaches?
Upvotes: 0
Views: 237
Reputation: 80265
Use parentContext
. This is preferred to the method with the persistent store coordinator since 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.
In your particular case:
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.
Source: NSManagedObjectContext class reference, "Parent Store".
Upvotes: 1