Working off the Main Queue

Now that threading with Core Data has been reduced to a binary question, the other type of NSManagedObjectContext we’ll look at is NSPrivateQueueConcurrencyType.

The primary difference between the two context types is what queue the context is associated with. When you’re working with an NSMainQueueConcurrencyType context, the context automatically associates itself with the main queue. When you initialize an NSPrivateQueueConcurrencyType context, the context will associate itself with a non-main queue that’s private to the context.

Private means that you can’t access that queue directly. Calling dispatch_sync or dispatch_async on that queue is against the API. The only way to interact with a private queue context is through -performBlock: and -performBlockAndWait:.

This difference also means that any interaction with the private queue context must be inside a -performBlock: or -performBlockAndWait: call. The three exceptions to that rule are -initWithConcurrencyType:, -setParentContext:, and -setPersistentStoreCoordinator:. Any other interaction with a private queue context must be wrapped in a block.

As with a main queue context, any objects created or retrieved from a private queue context can only be accessed on that private queue. If you attempt to access those objects outside the code block, then you’re violating the thread constraint rules of Core Data and will run into data integrity issues.