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.
Want more? Subscribers can view all 376 episodes. New episodes are released regularly.
Links
- Episode Source Code
- Careful with Block Based Notification Handlers - This is a blog post I wrote which indicates a small gotcha you have to be aware of when dealing with blocks.
- Concurrency Programming Guide - Apple's documentation on using blocks with GCD (Grand Central Dispatch) to make multi-threaded code much easier to read & write.
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;