28 Blocks

A block is a chunk of code. Here is a block:

^{
    NSLog(@"This is an instruction within a block.");
}

It looks like a C function; it is a set of instructions inside curly braces. It does not, however, have a name. Instead, the caret (^) identifies this bit of code as a block.

Like a function, a block can take arguments and return values. Here is another block:

^(double dividend, double divisor) {
    double quotient = dividend / divisor;
    return quotient;
}

This block takes two doubles as arguments and returns a double.

You can pass a block as an argument to a method that accepts a block. Many of Apple’s classes have methods that accept blocks as arguments.

For instance, NSArray, NSDictionary, and NSSet allow block-based ...

Get Objective-C Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.