Blocks to Basics in Objective-C

Blocks are one of the most fundamentally useful iOS technologies. If you're not pushing beyond system-supplied APIs and incorporating them into your day-to-day development, you're missing out on one of the most powerful Objective-C features. Discover some basic block how-tos and pick up a few tricks for your projects.

From the author of

From the author of

Blocks are one of the most fundamentally useful iOS technologies. You pass blocks to methods and functions as arguments so that they can be stored and executed at later times. Blocks enable you to move those implementation details away from isolated callbacks and into the actual context where they're most meaningful. This approach improves readability and inspection because the way items react before, during, and after some process are most relevant at the point where that process is defined.

First introduced in iOS 4, blocks create functional closures. Closures are objects that encapsulate both behaviors and state. Unlike method selectors and function pointers, blocks carry that state with them for when they're executed. This enables you to refer to variables defined in the parent's lexical scope from within the block itself. That means you don't have to pass massive numbers of parameters to blocks to keep them in sync. Block parameters instead reflect information that won't be available until the block is executed. This is crazy convenient, ensuring that any relevant state can be used exactly when it's needed.

Most iOS developers now regularly use blocks in their projects (see Figure 1) using system-supplied and custom APIs but there's often confusion as to exact implementation details. Various sites have sprung up to provide quick block syntax references including at least one with an honest but not-safe-for-work name. (It offers a more workplace friendly URL as well.) These sites reflect the fussy detail reality associated with block declaration and use.

I personally ended up writing an entire OS X application (see Figure 2) because while I love blocks to death, I can never quite remember exactly how to phrase them in code. I'll know I want to build a completion block, for example, that takes a success argument or a testing block that returns a Boolean value, but the minutia always is just one neuron beyond my working memory. My BlockItToMe utility (available on my website) helps avoid that pain.

Figure 2To avoid blocking on how to declare and use blocks, I wrote a utility to create a boilerplate

Auto Complete Is Your Friend

For many developers, a first exposure to blocks involves system-supplied APIs such as view animation. Xcode's autocomplete system, shown in Figure 3 (top), provides placeholder tokens for each argument. These are coded with a blue highlight. When you double-click any token, Xcode automatically expands it to further detail. For example, after expanding the completion parameter, Xcode creates the more detailed ready-to-use block outline you find in Figure 3's bottom screen shot.

Figure 3You don't have to remember how to construct block parameters because Xcode builds them for you

This same auto complete convenience applies to any method you build into your classes. In Figure 4, the block argument token expands into a block that uses strings for both its argument and return type. You'll never have to remember how to structure a method or function argument because Xcode takes care of that on your behalf.

Define Block Types

Block typedefs are incredibly useful. For example, say you're building a class whose instances performs an action and, when finished, permit you to execute an optional completion block. You can go the standard route and specify a full block argument declaration like this:

Alternatively you simplify matters by declaring a custom block type in your class header file. Here's an example that defines a type and then uses it in a method signature identical to the example you just saw.

With typedefs, you inherit the same Xcode auto complete features as you do with explicit block declarations. At the same time you increase code readability, and there's only one point where you have to worry about the fine details of how to specify the block type. The declaration consists of a return type followed by a type name and concludes with a parameter list. Include a caret (^) before your type name and use both sets of parentheses.

typedef <#return type#>(^<#type name#>)(<#parameter list#>);

Build Typed Block Variables

When you've defined a block type, you can declare and assign variables using that type. For example, you might use the custom completion block type you just saw to create an instance variable.

But what do you do when working with system-supplied APIs that don't use typedefs? If your custom type is equivalent to an argument, you may use your typed argument. For example, MyCustomCompletionBlock is identical to the completion argument used in UIView's animation call.

Declaring Block Variables

You're not required to use a typedef, of course, to assign block to variables. Use the following format to declare a block variable. Start with a return type followed by the variable name and a parameter list. You'll need a caret (^) before the variable name and two sets of parentheses.

<#return type#> (^<#variable name#>)(<#parameter list#>)

With that in mind, the following example declares a completion block, identical to the one you just saw, but without using custom typedefs.

void (^completion)(BOOL) = ^(BOOL finished){
NSLog(@"completed");
};

Use Block Properties

At times you may want to use properties instead of method arguments to hold onto blocks until you're ready to use them. The property declaration mirrors the form you use for creating local variables.

@property (nonatomic, copy) MyCustomCompletionBlock finished;

or

@property (nonatomic, copy) void (^completion)(BOOL finished);

Make sure you use the method accessor to ensure the property's copy attribute is applied. That is, use this

self.completion = ^(BOOL finished){
NSLog(@"completed");
}

rather than this.

_completion = ^(BOOL finished){
NSLog(@"completed");
}

Block Safety

With blocks, safety matters. If there's any chance a property has not been set or a parameter might be nil, make sure you test for the block before attempting to execute it. Here's an example of what that might look like.

if (self.completion)
self.completion(status);

And Figure 5 shows an example of what happens if you forget that step.