Tuesday, February 10, 2015

Using blocks in objective-c iOS7 and iOS8

blocks are a godsend and still people are reserved in using it. Perhaps it is because they don't know how to set it up. Here is a quick example on how to set it up.

In the .h file of whatever you are creating, make a new typedef for the block;

typedef void(^myCompletion)(BOOL complete);

This line shows that this is a "myCompletion" block and has one value going into it which a bool called complete. 

Next in the .h file create the method you want with a completion block;

-(void)doMyStuff withCompletion:(myCompletion)compBlock;

Now all you have to do is create it in your .m file;

-(void)doMyStuff withCompletion:(myCompletion)compBlock{
     //do the stuff you want to do 
     if (compBlock != nil) {
         compBlock(YES);
     }
}

This will do the method and then check if the compBlock is nil (protection) and if it is not nil, perform that block of functions as well. 

Technically you can do the block anywhere in the code, I am just using completion as an example since most of the time, that is where it is used. 

Now you actually want to use this method? Simple;

[myMethod doMyStuff withCompletion:^(BOOL complete) {
     if (complete){

          self.navController.topViewController.navigationItem.titleView = logoView; 
     }
}];

and there you have it. 

if you want another version, you can look here.
Stanford also has a nice video about using existing blocks here.