14_Objective-C Blocks

  • Blocks allow you to create distinct segments of code that can be passed around to methods or functions as if they were values.
  • Blocks are Objective-C objects which means they can be added to collections
  • They also have the ability to capture values from the enclosing scope

Simple Block declaration syntax

returntype (^blockName)(argumentType);

Simple block implementation

returntype (^blockName)(argumentType)= ^{};

void (^simpleBlock)(void) = ^{
    NSLog(@"This is a block");
};

We can invoke the block using

simpleBlock();

Blocks Take Arguments and Return Values

Blocks can also take arguments and return values just like methods and functions.

Here is a simple example to implement and invoke a block with arguments and return values.

double (^multiplyTwoValues)(double, double) = ^
(double firstValue, double secondValue) //arguments
{
     return firstValue * secondValue;
};
double result = multiplyTwoValues(2,4);
NSLog(@"The result is %f", result);

Blocks using type definitions

Here is a simple example using typedef in block.

Please note this sample doesn’t work on the online compiler for now. Use XCode to run the same.

Blocks are used more in iOS applications and Mac OS X. So its more important to understand the usage of blocks.

Example

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

Blog at WordPress.com.

Up ↑

%d bloggers like this: