Skip to content

Instantly share code, notes, and snippets.

@kmdarshan
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmdarshan/0957765a16b635802762 to your computer and use it in GitHub Desktop.
Save kmdarshan/0957765a16b635802762 to your computer and use it in GitHub Desktop.
Playing around with Blocks in Objective-C
@interface Pair : NSObject
@property (nonatomic, copy) void (^blockAsProperty)(int val);
+(void) displayBlock:(void(^)(int param))blockAsMethodParameter;
@end
@implementation Pair
+(void) displayBlock:(void(^)(int param)) blockAsMethodParameter{
blockAsMethodParameter(10);
}
@end
// blocks as typedef
typedef void(^callback)(BOOL success, id value);
// block with void return and no arguments
void(^voidBlock)() = ^{
NSLog(@"b");
};
voidBlock();
// blocks can be stored in arrays
NSArray *arrayblocks = [NSArray arrayWithObjects:voidBlock, voidBlock, nil];
for (void (^block)() in arrayblocks) {
block();
}
// block with void return and arguments
// you can extend it to many more arguments
void(^blockWithParameters)(int a, int b) = ^(int a, int b){
NSLog(@"a+b=%d", a+b);
};
blockWithParameters(10,20);
arrayblocks = [NSArray arrayWithObjects:blockWithParameters, blockWithParameters, nil];
for (void (^blockWithParameters)(int param1, int param2) in arrayblocks) {
blockWithParameters(100,20);
}
// blocks can also be used to return values
int(^blockWithReturnType)(int a) = ^(int a){
return a*a;
};
// assign a value from the block
int blockReturnValue = blockWithReturnType(100);
NSLog(@"return value %d", blockReturnValue);
// blocks as property
Pair *pair = [Pair new];
[pair setBlockAsProperty:^(int param) {
NSLog(@"block as property %d", param);
}];
pair.blockAsProperty(10);
// blocks as method parameter
[Pair displayBlock:^(int param) {
NSLog(@"displayBlock %d",param);
}];
// copying a block to use it in some other place
int salt = 42;
int(^m_storedBlock)(int param) = ^(int incoming){
return 2 + incoming + salt;
};
m_storedBlock = [^(int incoming){
return 2+incoming+salt;
} copy];
int outputValue = m_storedBlock(5);
NSLog(@"When we ran our stored block we got back: %d", outputValue);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment