Core Data Part 2 . — Child Contexts and Multiple Managed Object Contexts

Sejan Miah
killingMeSwiftly
Published in
2 min readJun 20, 2017

--

Multiple Managed Object Contexts

Core Data’s default configuration provides you with a single managed object associated with the main queue. To refresh a managed object context is an in-memory scratchpad you can use when working with your managed objects.

When might you want more than one managed object context?

1. Editing data → the managed object context can be treated as a set of changes, that the app can discard through child contexts. Edited data can be thought of as new pieces of information, like a scratch pad. Once the data is edited you either save or delete.

2. Exporting Data (long-running task) → blocks main thread of apps using just a single main-queue managed object context, UI is then blocked and not updating properly.

The default behavior when exporting data is to have both your export operation and the UI use the main queue to perform their work, but if this export is a long running task the UI will lag and there will be a delay. Traditionally, you could run the data exporting onto a background queue, but Core Data managed object contexts are not thread safe. You cannot dispatch the operation to a background queue and use the same Core Data Stack.

Some context about your context from Apple’s Developer Website:

In general, avoid doing data processing on the main queue that is not user-related. Data processing can be CPU-intensive, and if it is performed on the main queue, it can result in unresponsiveness in the user interface. If your application will be processing data, such as importing data into Core Data from JSON, create a private queue context and perform the import on the private context. The following example shows how to do this:

Let’s look at what’s happening in line 5. The new context was set as a child of the main context running the application. Child managed object contexts are temporary scratch pads, essentially it is a container for editable changes, that can be discarded or modified and saved with changes to the parent context. When a child context is saved, the changes only go to the parent context. When the parent context is saved, then the changes in the parent context get sent to the persistent store coordinator.

Furthermore, every managed object context has a parent store, usually it is the persistent store container if it is the main context provided by the CoreDataStack class.

--

--