Graphics Programs Reference
In-Depth Information
Typical Block Usage
In this chapter, our examples have been pretty trivial. In the next chapter, you will see some
real world examples of blocks and see just how useful they can be. However, to whet your
appetite a bit, let's talk about how blocks are typically used.
Most commonly, blocks are used as callbacks. For example, in Chapter 13 you supplied a
block when dismissing a modal view controller. When the dismissal completed, the block
was executed. Thus, you can think of blocks as a one-shot callback for an event to occur
some time in the future. We usually call a block used in this manner a completion block .
Using a completion block is usually much simpler than setting up a delegate or a target-ac-
tion pair. You don't have to declare or define a method or even have an object to set up the
callback, you just create a block before the event and let it fire. A block, then, is an object-
less callback, whereas every other callback mechanism we've used so far (delegation,
target-actions, notifications) must have an object to send a message to.
Blocks are used in a lot of system APIs. For instance, NSArray has a method named
sortedArrayUsingComparator: . When this message is sent, the array uses the
block to compare every object it holds and returns another array that has been sorted. It
looks like this:
NSArray *sorted = [array sortedArrayUsingComparator:
^NSComparisonResult(id obj1, id obj2) {
if ([obj1 value] < [obj2 value])
return NSOrderedDescending;
else if ([obj1 value] > [obj2 value])
return NSOrderedAscending;
return NSOrderedSame;
}];
When working with a method that takes a block, you must supply a block that matches the
signature declared by the method. For one thing, the compiler will give you an error if you
supply a different kind of block. But also, the block has a specific signature for a reason:
the method that uses it will expect it to work in a certain way. You can think of blocks used
in this way as a “plug-in.” NSArray says, “Hey, I got these objects, and I can feed them to
your block to figure out which ones go where. Just give me the specifics.”
There are many other ways to use blocks, like queuing up tasks (a block that calls a block
that calls another block), and some objects that use blocks know how to spread the execu-
Search WWH ::




Custom Search