Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Blocks cheat sheet
// http://cocoawithlove.com/2009/10/ugly-side-of-blocks-explicit.html has a nice breakdown of the syntax--it helps to think of the ^ as similar to a pointer dereference symbol *
// block typedef:
typedef void(^Block)();
typedef void(^ConditionalBlock)(BOOL);
typedef NSString*(^BlockThatReturnsString)();
typedef NSString*(^ConditionalBlockThatReturnsString)(BOOL);
// block property with typedef:
@property(copy)Block theBlock;
// block property without typedef:
@property(copy)void(^block)();
@property(copy)void(^conditionalBlock)(BOOL);
@property(copy)NSString*(^blockThatReturnsString)();
@property(copy)NSString*(^conditionalBlockThatReturnsString)(BOOL);
// block definition inline:
ReturnType(^block_name)(parmeter, types, here) = ^(parameter, types, here) {};
void(^block)(void) = ^{};
void(^conditionalBlock)(BOOL shouldWork) = ^(BOOL shouldWork){};
NSString*(^blockThatReturnsString)(void) = ^ NSString* { return @"foo"; };
NSString*(^conditionalBlockThatReturnsString)(BOOL shouldWork) = ^ NSString* (BOOL shouldWork){
return shouldWork ? @"foo" : @"bar";
};
-(void)runBlocks {
block();
conditionalBlock(NO);
NSString *someString = blockThatReturnsString();
NSString *conditionalString = conditionalBlockThatReturnsString(NO);
}
// blocks as return values:
-(void (^)(void))doSomething;
-(void (^)(BOOL))doSomethingConditionally;
-(NSString* (^)(void))returnString;
-(NSString* (^)(BOOL))returnStringConditionally;
-(NSString* (^)(BOOL))returnStringConditionally {
return ^(BOOL shouldReturn) {
if (shouldReturn) return @"foo";
return @"bar";
}
}
// blocks as arguments:
-(void)doSomethingWithBlock:(void (^)(void))block;
-(void)doSomethingWithBlock:(void (^)(BOOL))conditionalBlock;
-(void)doSomethingWithBlock:(NSString* (^)(void))blockThatReturnsString;
-(void)doSomethingWithBlock:(NSString* (^)(BOOL))conditionalBlockThatReturnsString;
@lytzen

This comment has been minimized.

Copy link

commented Sep 28, 2013

Great sheet! I don't use blocks as much as I'd like to, because I can never remember how to. This is a great help.
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.