Marcin Kapusta
Marcin Kapusta

Reputation: 5366

Core Data API usage best patterns in iOS 10

I was looking last time for some books related to Core Data in iOS 10, especially covering subjects like Query Generations, NSPersistentContainer, how to setup my Contexts hierarchy in new API with their new concurrency model, and so on.

I read that now every context should have their parents set to nil, and the best way is to connect every Context directly to the Persistent Story Coordinator. There is no need to setup parent/child relationships between context if our goal is to responsive UI in our application. I have questions such as:

  1. Do I need to use the container.newBackgroundContext() method to create context each time I need some task to perform in background or should I create one context and store it somewhere and reuse it for better performance? How many context I can create? What is the best number of background contexts?
  2. Do I need to setup the container.viewContext parent to some private context created from container.newBackgroundContext()?
  3. What is the best approach to create a background task that is updating some data in the background thread on not main queue and inform about this main viewContext?
  4. What is the best way to inform background context that about changes in model that user introduced in main viewContext in UI?
  5. Do you know some books that covers those topics including architecture and concurrency changes in iOS 10?

Upvotes: 2

Views: 841

Answers (2)

Jerry
Jerry

Reputation: 4480

If you set automaticallyMergesChangesFromParent to true on any context, it will merge changes from any parent context. In iOS 10, any contexts created by the NSPersistentContainer have the container's NSPersistentStoreCoordinator as a parent. The effect is that if you set this to true on your viewContext, changes saved on any newBackgroundContext will automatically merge and vice versa.

Upvotes: 2

Abizern
Abizern

Reputation: 150565

  1. You don't generally need to do this. Create a background context for a particular task and then tear it down. Alternatively, NSPersistentContainer has a method performBackgroundTask(): just pass a block to this and it will create a new private context for you to run this block.
  2. Nope. NSPersistentContainer deals with that for you.
  3. If you observe the viewContext for changes, then as long as you do a save in any of your background queues, this change will percolate up. Alternatively, use an NSFetchResultsController which has a lot of delegate methods that help you respond to changes.
  4. You don't need to do this. Just do what you need to in a private queue and your merge policy will dictate what happens for conflicts.
  5. Unfortunately, the changes are still relatively new. Read the documentation for NSPersistentContainer and also the What's New in Core Data page.

Upvotes: 4

Related Questions