Blocks Syntax and its Variants

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

This post is specifically to me. I am not sure why I am not able to remember this simple syntax of the passing blocks as parameter.

 

So here it is.. Its very similar to C function pointers

<return type> (* [<function pointer name>])( [parameter1, parameter2….])

The only difference is to replace * to ^.  <function pointer name> is name of the block, Lets call its as as <block name>.  if you are using this directly to pass a block as  a parameter to a method, then the <block name> is not needed.

 

For Example, You declare a method which accepts a block as a parameter like this:

-(void)performLongOperation:( void (^)(NSError *error, id result))completionBlock;


Variants of Creating and Defining a Block


a. Block definition as part of method invocation:

 

One would invoke the block within the performLongOperation method definition as:

NSError * error = nil;

id result = nil;

..

..

..

completionBlock(error, result );

The caller would look like:

  [self performLongOperation: ^(NSError *error, id result){

        //what you want to do after performLongOperation?

    }];

This is one of the way where the whole body of the block is written as part of method invocation.

 

 

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

b. Block as a variable OR a named Block:

 

If the above code snippet looks complicated (esp. if the callback is very lengthy) or if there is a need to separate the callback from the caller, then you can give a name to a block like this:

  void (^ myblock )(NSError *, id result)  = ^(NSError *error, id result){

        //what you want to do after performLongOperation?

    };

where myblock is the name of the block. The method invocation would look like:

    [self performLongOperation: myblock];


c. Block as a custom data type


In some cases, we might want to pass a different callback functions based on certain conditions and in order to do that we can create our own custom data type using typedef.

typedef void (^my_block_type)(NSError *, id );

and create a block variable of type my_block_type which accepts two parameters of type NSError and id and returns nothing.

my_block_type validate_long_operation_result = ^(NSError *error, id result){

        //validate result

    };

 

my_block_type divert_to_second_operation = ^(NSError *error, id result){

        //do second operation

    };

Caller would look like this:

[self performLongOperation: ( should_chose_second_operation ? divert_to_second_operation :  validate_long_operation_result)];

 

Click Me for More Info on Basics of Blocks


Happy Coding 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *