Home > Articles > Mobile Application Development & Programming

Blocks to Basics in Objective-C

  • Print
  • + Share This
  • 💬 Discuss
From the author of
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.

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.

Figure 1 In modern iOS development, we are all blockheads (Image courtesy of LiveAuctioneers)

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 2 To 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 3 You 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.

Figure 4 Xcode block-expanding autocomplete isn't just for system-supplied APIs

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:

- (void) performWithCompletion: (void (^)(BOOL finished)) completionBlock;

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.

typedef void (^MyCustomCompletionBlock)(BOOL finished);
- (void) performWithCompletion: (MyCustomCompletionBlock) completionBlock;

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.

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

You can then use that block as an argument, for example:

[self performWithCompletion:completion];

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.

+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion

This enables you to pass the completion variable defined above to this animation method. In this example, when the animation concludes, the completion block logs "completed".

[UIView animateWithDuration:0.5f animations:^{
        self.view.backgroundColor = [UIColor clearColor];
    } completion:completion];

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.

Figure 5 Executing unassigned blocks crashes your application

Executing a nil block will crash your application so consider using one of the following approaches to add further safety to your apps.

  • Nonnull attributes. When you declare parameters using a nonnull attribute, Xcode raises a warning if you pass nil. (See Figure 6)
- (void) foo: (ABlockType) blockParameter __attribute__ ((nonnull))
{
    //....
}
  • Parameter assertions. The NSParameterAssert function tests whether a parameter is nil and raises an NSInternalInconsistencyException exception if it is.
- (void) foo: (ABlockType) blockParameter
{
    // blockParameter must not be nil
    NSParameterAssert(blockParameter);
}

Figure 6 The nonnull attribute tells the compiler to warn when a required parameter is null

Wrap Up

You just got a short taste of some ways you can expand your use of blocks in iOS development. Here are a few key points to keep with you.

  • If you're not using typedefs with your blocks, you're missing out on one of the best solutions for simplifying your code.
  • Emulate Apple and consider adapting classes to use completion blocks. Properties enable your instances to hold onto those until they're ready to use them.
  • Don't forget to stop by any of the blocks quick reference sites mentioned in this write-up. They, plus my BlockItToMe utility, can help you get your block syntax just right.
  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus