Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Objective-C.Programming.pdf
Скачиваний:
14
Добавлен:
21.02.2016
Размер:
8.64 Mб
Скачать

32

Blocks

In Chapter 24, you learned about the callback mechanisms delegation and notifications. Callbacks allow other objects to call methods in your object in response to events. While perfectly functional, these approaches break up your code. Pieces of your program that you’d like to be close together for clarity’s sake usually aren’t.

For example, in your Callbacks program from Chapter 24, you added code to register your object for a notification when the user’s time zone changes and to set zoneChange: to be triggered when this notification is received. But now I’m reading your code and curious about what this zoneChange: method does when it is triggered, so I go looking for the implementation of this method. In the Callbacks example, the code that registers the object for a notification and the implementation of the

method that is triggered are right next to each other, but you can imagine that in a larger, more complex application, these two pieces of code could be hundreds of lines away from each other.

Mac OS X 10.6 and iOS 4 introduced a new feature called blocks. An Objective-C block is just a chunk of code like a C function, but it can be passed around as data. We’ll see shortly how this keeps relevant code together.

Blocks and block syntax are definitely an advanced Objective-C topic and can be confusing at first. However, Apple’s APIs are using blocks more and more. In this chapter, we’ll step through a couple of simple examples so that you’ll be ready when you encounter blocks in the wild.

If you have a background in another programming language, you might know blocks as anonymous functions, closures, or lambdas. If you’re familiar with function pointers, blocks may appear to be similar, but you’ll soon see that proper use of blocks allows for more elegant code than can be written with function pointers.

Defining blocks

This is a block:

^{

NSLog(@"I'm a log statement within a block!");

}

This looks like a function, but it has a caret (^) instead of a function name. The caret identifies this bit of code as a block. Also, like a function, a block can take arguments:

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

}

227

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]