Using Blocks
In Objective-C 2.0, blocks refer to a language construct that supports “closures,” a way of treating code behavior as objects. First introduced to iOS in the 4.0 SDK, Apple’s language extension makes it possible to create “anonymous” functionality, a small coding element that works like a method without having to be defined or named as a method.
This allows you to pass that code as parameters, providing an alternative to traditional callbacks. Instead of creating a separate “doStuffAfterTaskHasCompleted” delayed execution method and using the method selector as a parameter, you can use blocks to pass that same behavior directly into your calls. This has two important benefits.
First, blocks localize code to the place where that code is used. This increases maintainability and readability, moving code to the point of invocation. This also helps minimize or eliminate the creation of single-purpose methods.
Second, blocks allow you to share lexical scope. Instead of explicitly passing local variable context in the form of callback parameters, blocks can implicitly read locally declared variables and parameters from the calling method or function. This context-sharing provides a simple and elegant way to specify the ways you need to clean up or otherwise finish a task without having to re-create that context elsewhere.
Defining Blocks in Your Code
Closures have been used for decades. They were introduced in Scheme (although they were discussed in computer science books, papers, and classes since the 1960s), and popularized in Lisp, Ruby, and Python. The Apple Objective-C version is defined using a caret symbol, followed by a parameter list, followed by a standard block of code, delimited with braces. Here is a simple use of a block. It is used to show the length of each string in an array of strings:
NSArray *words = [@"This is an array of various words" componentsSeparatedByString:@" "]; [words enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSString *word = (NSString *) obj; NSLog(@"The length of '%@' is %d", word, word.length); }];
This code enumerates through the “words” array, applying the block code to each object in that array. The block uses standard Objective-C calls to log each word and its length. Enumerating objects is a common way to use blocks in your applications. This example does not highlight the use of the idx and stop parameters. The idx parameter is an unsigned integer, indicating the current index of the array. The stop pointer references a Boolean value. When the block sets this to YES, the enumeration stops, allowing you to short-circuit your progress through the array.
Block parameters are defined within parentheses after the initial caret. They are typed and named just as you would in a function. Using parameters allows you to map block variables to values from a calling context, again as you would with functions.
Using blocks for simple enumeration works similarly to existing Objective-C 2.0 “for in” loops. What blocks give you further in the iOS SDK 4 APIs are two things. First is the ability to perform concurrent and/or reversed enumeration using the enumerateObjectsAtIndexes:options:usingBlock: method. This method extends array and set iteration into new and powerful areas. Second is dictionary support. Two methods (enumerateKeysAndObjectsUsingBlock: and enumerateKeysAndObjectsWithOptions:usingBlock:) provide dictionary-savvy block operations with direct access to the current dictionary key and object, making dictionary iteration cleaner to read and more efficient to process.
Assigning Block References
Because blocks are objects, you can use local variables to point to them. For example, you might declare a block as shown in this example. This code creates a simple maximum function, which is immediately used and then discarded:
// Creating a maximum value block float (^maximum)(float, float) = ^(float num1, float num2) { return (num1 > num2) ? num1 : num2; }; // Applying the maximum value block NSLog(@"Max number: %0.1f", maximum(17.0f, 23.0f));
Declaring the block reference for the maximum function requires that you define the kinds of parameters used in the block. These are specified within parentheses but without names (that is, a pair of floats). Actual names are only used within the block itself.
The compiler automatically infers block return types, allowing you to skip specification. For example, the return type of the block in the example shown previously is float. To explicitly type blocks, add the type after the caret and before any parameter list, like this:
// typing a block float (^maximum)(float, float) = ^float(float num1, float num2) { return (num1 > num2) ? num1 : num2; };
Because the compiler generally takes care of return types, you need only worry about typing in those cases where the inferred type does not match the way you’ll need to use the returned value.
Blocks provide a good way to perform expensive initialization tasks in the background. The following example loads an image from an Internet-based URL using an asynchronous queue. When the image has finished loading (normally a slow and blocking function), a new block is added to the main thread’s operation queue to update an image view with the downloaded picture. It’s important to perform all GUI updates on the main thread, and this example makes sure to do that.
// Create an asynchronous background queue NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease]; [queue addOperationWithBlock: ^{ // Load the weather data NSURL *weatherURL = [NSURL URLWithString: @"http://image.weather.com/images/maps/current/curwx_600x405.jpg"]; NSData *imageData = [NSData dataWithContentsOfURL:weatherURL]; // Update the image on the main thread using the main queue [[NSOperationQueue mainQueue] addOperationWithBlock:^{ UIImage *weatherImage = [UIImage imageWithData:imageData]; imageView.image = weatherImage;}];
This code demonstrates how blocks can be nested as well as used at different stages of a task. Take note that any pending blocks submitted to a queue hold a reference to that queue, so the queue is not deallocated until all pending blocks have completed. That allows me to create an autoreleased queue in this example without worries that the queue will disappear during the operation of the block.
Blocks and Local Variables
Blocks are offered read access to local parameters and variables declared in the calling method. To allow the block to change data, the variables must be assigned to storage that can survive the destruction of the calling context. A special kind of variable, the __block variable, does this by allowing itself to be copied to the application heap when needed. This ensures that the variable remains available and modifiable outside the lifetime of the calling method or function. It also means that the variable’s address can possibly change over time, so __block variables must be used with care in that regard.
The following example shows how to use locally scoped mutable variables in your blocks. It enumerates through a list of numbers, selecting the maximum and minimum values for those numbers.
// Using mutable local variables NSArray *array = [@"5 7 3 9 11 13 1 2 15 8 6" componentsSeparatedByString:@" "]; // assign min and min to block storage using __block __block uint min = UINT_MAX; __block uint max = 0; [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { // update the max and min values while enumerating min = MIN([obj intValue], min); max = MAX([obj intValue], max); // display the current max and min NSLog(@"max: %d min: %d\n", max, min); }];
Blocks and Memory Management
When using blocks with standard Apple APIs, you will not need to retain or copy blocks. When creating your own blocks-based APIs, where your block will outlive the current scope, you may need to do so. In such a case, you will generally want to copy (rather than retain) the block to ensure that the block is allocated on the application heap. You may then autorelease the copy to ensure proper memory management is followed.
Other Uses for Blocks
In this section, you have seen how to define and apply blocks. In addition to the examples shown here, blocks play other roles in iOS development. Blocks can be used with notifications (see example in Chapter 1), animations, and as completion handlers. Many new iOS 4 APIs use blocks to simplify calls and coding. You can easily find many block-based APIs by searching the Xcode Document set for method selectors containing “block:” and “handler:”.