Using Blocks in iOS

October 1st, 2011 Leave a comment Go to comments

A block encapsulates a chunk of code that can be passed around and used without being wrapped in a function. Blocks are present and widely used in languages like Ruby (called blocks) and JavaScript (called inline functions). Blocks are part of Objective C 2.0 and support for blocks was added with the release of iOS 4.0. Block is not a widely used construct in Objective C but it is a powerful feature that allows the possibility to create closures. You can create a block in objective C as follows:

int (^my_block)(NSString *) = ^(NSString *name) {
NSLog(@"Welcome %@!", name);
};

You invoke a block just like you would invoke any function in C.

my_block(@"Joe");

Blocks can also act as closures. Blocks close around the variables that are in their scope at the time of the block declaration. For example:

NSUInteger times = 4;

void (^print_message)(NSArray *) = ^(NSString *msg) {
for (NSUInteger i = 0; i <times; i++) {
NSLog(@"%@\n", msg);
}
};

print_message("Hello World!");      // prints ‘Hello World!’ 4 times

/* Output:
HelloWorld!
HelloWorld!
HelloWorld!
HelloWorld!
*/

times = 10;

print_message("Goodbye!");        // prints ‘Goodbye!’ 4 times

/* Output:
Goodbye!
Goodbye!
Goodbye!
Goodbye!
*/

As you can see in the example above, initial value of times variable is 4, therefore the “Hello World!” message is printed four times. When the value of ‘times’ variable is updated, the closed variable in the block (closure) is still 4. That is why the “Goodbye!” message is also printed four times.
Apple has updated its Cocoa framework to add methods that take anonymous block as an argument. An example of one such function is given below:

NSArray *colors = [NSArray arrayWithObjects:
@"red",
@"blue",
@"green",
@"yellow",
nil];

[colors enumerateObjectsUsingBlock: ^(id object, NSUInteger index, BOOL *stop) {
NSLog(@"Color %d: %@\n", index, object);
}];

/* Output:
Color 1: red
Color 2: blue
Color 3: green
Color 4: yellow
*/
  1. No comments yet.

Leave a reply

 
 
 


3 × nine =