Reputation: 15512
Previously in the application i was using multi context approach to use background context to do manipulation with data in the background thread. It was done like this.
// backgroundContext in the background thred
lazy var backgroundContext: NSManagedObjectContext? = {
let coordinator = self.store.persistentStoreCoordinator
var backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
backgroundContext.persistentStoreCoordinator = coordinator
return backgroundContext
}()
And it was used like this:
self.coreDataManager.saveContext(self.coreDataManager.backgroundContext!)
How with new CoreData update we should handle multiple CoreData contexts? Because now with NSPersistentContainer
it should be handled a bit in another way.
Upvotes: 2
Views: 2200
Reputation: 1075
According to Apple's own documentation available here, and the What's new in Core Data talk, this is the recommended way to do it:
let container = NSPersistentContainer.persistentContainerWithName("myApp")
container.performBackgroundTask() { (moc) in
// use moc to do asynchronous work
}
By default, the NSPersistentContainer provides a context for UI related tasks, ViewContext
, and the ability to create as many background contexts you may need, by doing:
let moc = container.newBackgroundContext
Notice though, that int the talk they recommend the use of performBackgroundTask()
instead of creating your own background context. This is because the said method does some optimizations that wouldn't take place if you use the context by yourself.
Upvotes: 5