Fun with Blocks

Episode #10 | 21 minutes | published on April 4, 2012
Free Video
Blocks are a great way to simplify code when dealing with asynchronous tasks (using GCD), callbacks, and atomic operations. In this episode, we'll look at a few ways you can use blocks in your code.


Creating a Block with no Arguments

^ {
  // block code here

Using a block as a method parameter

If you want to accept a block as a method parameter, you can type out the cryptic syntax, but it's not very easy to read (or write).

This method accepts a block. The block accepts a BOOL parameter and must return an NSString.

- (void)someMethodWithBlock:(NSString * (^)(BOOL))block;

To make this more usable elsewhere in the code, you can use a typedef instead. Put this somewhere in your header file:

typedef NSString * (^CrazyBlock)(BOOL animated);

Then you can update where it's used:

- (void)someMethodWithBlock:(CrazyBlock)block;
blog comments powered by Disqus