Blocks & Completion Handlers

Blocks in iOS for Completion Handlers by Marcio Valenzuela Santiapps.com
Blocks in iOS for Completion Handlers by Marcio Valenzuela Santiapps.com

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++;

}

completed(YES);

}

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!

Advertisements

One thought on “Blocks & Completion Handlers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s