Blocks in Objective-C

This is a syntax cheatsheet for blocks in Objective-C. I happen to like blocks a lot, so here's what I've come across. For more detailed reference refer to the Block Programming Guide on Apple's Developer Documentation site.

As a Method Argument

Creating a block as a method argument is commonly used for async operation, such as calling out to an API. Below is a block that contains a single boolean argument.

+(void) verifyPublishPermission:(void (^)(bool allowed))callback;

Below is another example of the same block but with three arguments that get passed to the block.

+(void) verifyPublishPermission:(void (^)(bool allowed, id result, NSError* error))callback;

The block is specified by the caller as such:

-(void) someFunction
{
   // do some stuff

   // call my function with a block as an agurment
   [MyAPI verifyPublishPermissions:^(bool allowed, id result, NSError *error) 
   {
       // do some stuff    
   }];
}

As a Local Variable

You may sometimes want to declare a block as variable to avoid code duplication.

-(void) someFunction2
{
   // store my block in variable named repeatCode
   void(^repeatCode)(bool allowed) = ^(bool allowed) 
   {
      // code
   }

   // invoke my block directly
   repeatCode(true);

   // or pass to a function as a callback   
   [MyAPI verifyPublishPermission:repeatCode];
}
comments powered by Disqus