Episode #10

Fun with Blocks

21 minutes
Published on April 4, 2012
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.

Links

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;
Want more? Subscribers can view all 574 episodes. New episodes are released regularly.

Subscribe to get access →

Source Code

View on GitHub Download Source