What is NSManagedObjectContext's performBlock: used for?

nevan king picture nevan king · Mar 29, 2012 · Viewed 30.9k times · Source

In iOS 5, NSManagedObjectContext has a couple of new methods, performBlock: and performBlockAndWait:. What are these methods actually used for? What do they replace in older versions? What kind of blocks are supposed to be passed to them? How do I decide which to use? If anyone has some examples of their use it would be great.

Answer

MikeG picture MikeG · Apr 4, 2012

The methods performBlock: and performBlockAndWait: are used to send messages to your NSManagedObjectContext instance if the MOC was initialized using NSPrivateQueueConcurrencyType or NSMainQueueConcurrencyType. If you do anything with one of these context types, such as setting the persistent store or saving changes, you do it in a block.

performBlock: will add the block to the backing queue and schedule it to run on its own thread. The block will return immediately. You might use this for long persist operations to the backing store.

performBlockAndWait: will also add the block to the backing queue and schedule it to run on its own thread. However, the block will not return until the block is finished executing. If you can't move on until you know whether the operation was successful, then this is your choice.

For example:

__block NSError *error = nil;
[context performBlockAndWait:^{
    myManagedData.field = @"Hello";
    [context save:&error];
}];

if (error) {
    // handle the error.
}

Note that because I did a performBlockAndWait:, I can access the error outside the block. performBlock: would require a different approach.

From the iOS 5 core data release notes:

NSManagedObjectContext now provides structured support for concurrent operations. When you create a managed object context using initWithConcurrencyType:, you have three options for its thread (queue) association

  • Confinement (NSConfinementConcurrencyType).

    This is the default. You promise that context will not be used by any thread other than the one on which you created it. (This is exactly the same threading requirement that you've used in previous releases.)

  • Private queue (NSPrivateQueueConcurrencyType).

    The context creates and manages a private queue. Instead of you creating and managing a thread or queue with which a context is associated, here the context owns the queue and manages all the details for you (provided that you use the block-based methods as described below).

  • Main queue (NSMainQueueConcurrencyType).

    The context is associated with the main queue, and as such is tied into the application’s event loop, but it is otherwise similar to a private queue-based context. You use this queue type for contexts linked to controllers and UI objects that are required to be used only on the main thread.