O'Reilly logo

Learning Cocoa with Objective-C, 3rd Edition by Jonathon Manning, Paris Buttfield-Addison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Blocks and Operation Quotes

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 is captured ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required