18.9. Fetching Data in the Background

Problem

You want to perform fetches in your Core Data Stack, all in the background. This is great if you want to ensure that you have a responsive user interface.

Solution

Before performing background fetches, create a new managed object context with the concurrency type of NSPrivateQueueConcurrencyType. Then use the performBlock: method of your new background context to perform your fetches in the background. Once you are done and are ready to use your fetched objects in your UI, go back to the UI thread using dispatch_async (see Recipe 7.4) and for every object that you fetched in the background, issue the objectWithID: method on your main context. This will bring those background-fetched objects to your foreground context, ready to be used in your UI thread.

Discussion

Fetching on the main thread is not a good idea unless you have a very limited number of items in your Core Data stack, because a fetch generally issues a search call to Core Data. It then has to fetch some data for you, usually using a predicate. To make your UI more responsive, it’s best that you issue your fetches on a background context.

You can have as many contexts as you want in your app, but there is one golden rule here. You cannot pass managed objects between contexts on different threads, because the objects are not thread safe. That means that if you fetch objects on a background context, you cannot use them on the main thread. The correct way of passing managed objects ...

Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.