Chapter 6. Blocks and Operation Queues

Over the years, OS X and iOS have provided increasingly simple ways for developers to manage their code. Two of these features are blocks, which allow you to store chunks of code in variables and call them later, and operation queues, which dramatically simplify how you write applications that do multiple things at once.

These two features are closely tied together, and, once mastered, quickly become indispensable in developing applications.

In this chapter, you’ll learn how to code with blocks, what they’re good for, and how to use them in conjunction with operation queues, a powerful tool for performing tasks in the background.

Blocks

It’s often useful to be able to store code in variables. Consider the following code sample:

int i = 53;
void (^someCode)() = ^{
    NSLog(@"The value of i is %i", i);
};

In Objective-C, this is called a block. Blocks store code, and can be assigned to variables, passed to functions, and generally treated like any other value. The big feature is that blocks can be called like functions, and they capture the state of things as they were when the block was created.

Calling a block is identical to calling a function:

someCode(); // prints out "The value of i is 53".

Note that the block remembered that the variable i was 53 because it captured the state of that variable when it was created. When a variable outside a block is referenced within that block, the value of that variable at the moment of the block’s creation ...

Get Learning Cocoa with Objective-C, 4th Edition 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.