Blocks in iOS for Completion Handlers by Marcio Valenzuela
Blocks in iOS for Completion Handlers by Marcio Valenzuela

Think of blocks as c functions:

(return type)functionName(input1, input2) { input1 + input2 }

and you call it like this:

return type = functionName (1,2)

Blocks are similar:

NSInteger (^mathOperation)(NSInteger x, NSInteger y) = ^NSInteger(NSInteger x,NSInteger y){ return x + y; };

You call it like this:

NSInteger sum = mathOperation(1,2);

Now imagine how cool it is to, instead of just passing a value to a method (like saying: here is a value, evaluate it), you can pass a whole method to it (like saying: here is something else to do!). Or better yet, here do this but only when you finish doing that! Like, load the users posts or tweets after you finish authenticating him! This is the called method:

-(void)countToTenThousandAndReturnCompletionBLock:(void (^)(BOOL))completed{

int x = 1;

while (x < 10001) {

NSLog(@”%i”, x); x++;




This method takes a block and that block takes a Boolean.

And this is the calling method:

NewSimpleCounter *newSimpleCounter = [[NewSimpleCounter alloc] init];

[newSimpleCounter countToTenThousandAndReturnCompletionBLock:^(BOOL completed){

if(completed) {

NSLog(@”Ten Thousands Counts Finished”);



So we call the method and say to it:

“Count to 10,000 and when you are done, here is a block to execute”. So it counts and when it’s done, it sends YES to the block. Then it evaluates the block and since it’s yes, it completes!

One Comment

Leave a Reply