Group Group Group Group Group Group Group Group Group Forums

Multiple Managed Object Contexts with Core Data Tutorial

Learn how to use multiple managed object contexts to improve the performance of your apps in this Core Data Tutorial in Swift!

This is a companion discussion topic for the original entry at

Could you compare how this plays with the NSPersistantCoordinator introduced in iOS 10?

It seems there is something wrong with the code.
it’s unnecessary to change code in SegueListToDetail block but should change code in SegueListToDetailAdd block

else if segue.identifier == “SegueListToDetailAdd” {

  guard let navigationController = segue.destination as? UINavigationController,
    let detailViewController = navigationController.topViewController as? JournalEntryViewController else {
      fatalError("Application storyboard mis-configuration")
  let childContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
  childContext.parent = coreDataStack.mainContext
  let newJournalEntry = JournalEntry(context: childContext)

  detailViewController.journalEntry = newJournalEntry
  detailViewController.context = childContext
  detailViewController.delegate = self

then newly add and cancel will not have side effect on the store

I believe you’re referring to NSPersistentContainer as NSPersistantCoordinator has been around for a while?

NSPersistentContainer is just a new class that simplifies creating a new Core Data stack. This project already makes use of it if you look at CoreDataStack.swift.

With NSPersistentContainer you can still create child context or sibling context like you always have.

Susan, you are correct. This is actually not the full chapter. In the book version there is a challenge at the very end that ask the student to do exactly what you said.

With your newfound knowledge, try to update SegueListToDetailAdd to use a child context when adding a new journal entry.

I was just wandering, you set child context concurrency type to mainQueueConcurrencyType, because it was fast operation, so no point in setting it in background, right? Otherwise you would use PrivateQueueConcurrencyType, with childContext.perform()?

I used MainQueueConcurrencyType, the default type, to specify that the context will be associated with the main queue. This type is what the main context (coreDataStack.mainContext) uses. Any UI operation, such as creating the fetched results controller for the table view, must use a context of this type.

Any time you’re interacting with UIKit you should stick to the main queue.

As far as setting up your default database (the data the appears the first time you run)… It’s not necessary to copy the shm database file, right? That’s just a temporary file.

This tutorial is more than six months old, so questions regarding it are no longer supported. We will update it as soon as possible. Thank you! :]