-
-
Save aschuch/6476416 to your computer and use it in GitHub Desktop.
Blocks cheat sheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Blocks cheat sheet | |
*/ | |
/////////////////////////////////// | |
#pragma mark - block typedef | |
/////////////////////////////////// | |
typedef void(^Block)(); | |
typedef void(^ConditionalBlock)(BOOL); | |
typedef NSString*(^BlockThatReturnsString)(); | |
typedef NSString*(^ConditionalBlockThatReturnsString)(BOOL); | |
/////////////////////////////////// | |
#pragma mark - block as property | |
/////////////////////////////////// | |
@property(copy)Block theBlock; | |
@property(copy)void(^block)(); | |
@property(copy)void(^conditionalBlock)(BOOL); | |
@property(copy)NSString*(^blockThatReturnsString)(); | |
@property(copy)NSString*(^conditionalBlockThatReturnsString)(BOOL); | |
/////////////////////////////////// | |
#pragma mark - 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); | |
} | |
/////////////////////////////////// | |
#pragma mark - 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"; | |
} | |
} | |
/////////////////////////////////// | |
#pragma mark - blocks as arguments | |
/////////////////////////////////// | |
- (void)doSomethingWithBlock:(void (^)(void))block; | |
- (void)doSomethingWithBlock:(void (^)(BOOL))conditionalBlock; | |
- (void)doSomethingWithBlock:(NSString* (^)(void))blockThatReturnsString; | |
- (void)doSomethingWithBlock:(NSString* (^)(BOOL))conditionalBlockThatReturnsString; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment