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

typedef

[[NSNotificationCenter defaultCenter] addObserver:logger

selector:@selector(zoneChange:)

name:NSSystemTimeZoneDidChangeNotification

object:nil];

you identify a method (typically using @selector()), and then you implement that method somewhere else in the file:

- (void)zoneChange:(NSNotification *)note

{

NSLog(@"The system time zone has changed!");

}

You could use the NSNotificationCenter method addObserverForName:object:queue:usingBlock: and pass a block instead. With this method, you hand the NSNotificationCenter the instructions right then, so you don’t have to put the code for the callback somewhere else. Anyone reading your code will see the instructions and the message send to the NSNotificationCenter in the same chunk of code. (You’ll get to make exactly this change to your Callbacks program in a challenge at the end of the chapter.)

typedef

Block syntax can be confusing, but you can make it friendlier using the typedef keyword that you learned about in Chapter 10. Remember that typedefs belong at the top of the file or in a header, outside of any method implementations. In main.m, add the following line of code:

#import <Foundation/Foundation.h>

typedef void (^ArrayEnumerationBlock)(id, NSUInteger, BOOL *);

int main (int argc, const char * argv[])

{

Notice that this looks identical to a block variable declaration. However, here we are defining a type rather than a variable, so we put an appropriate type name next to the caret. This allows us to simplify declarations of similar blocks. Instead of declaring devowelizer this way

void (^devowelizer)(id, NSUInteger, BOOL *);

you can replace that line with the following declaration:

ArrayEnumerationBlock devowelizer;

This makes your block variable declaration a bit more familiar. Note that the block type itself only defines the block’s arguments and return types; it has no bearing on the set of instructions within a block of that type.

Return values

Finally, when a block returns a value, you can call its block variable like a function.

double (^divBlock)(double,double) = ^(double k, double j) { return k/j;

}

233

Chapter 32 Blocks

In this code, you’ve declared divBlock as a block variable that returns a double and expects two doubles as arguments. Then you assigned it a value which includes the instruction to return the result of dividing the two arguments.

You can use this block like so:

double quotient = divBlock(42.0, 12.5);

Memory management

Like primitive variables, blocks are created and stored on the stack. That is, the block will be destroyed along with the stack frame when the function or method that created the block returns. Sometimes, however, your block needs to live longer than that. For example, it could become an instance variable of an object. In this case, you must copy your block from the stack to the heap.

To copy a block from the stack to the heap, you send it the copy message:

ArrayEnumerationBlock iVarDevowelizer = [devowelizer copy];

Now a copy of your block exists on the heap. It is now a heap-based block instead of a stack-based block, and the new block variable is a pointer to the block.

Methods that take blocks as arguments, such as NSArray’s enumerateObjectsUsingBlock: or

NSNotificationCenter’s addObserverForName:object:queue:usingBlock:, are expected to copy blocks passed to them to keep them around. In doing so, they create pointers – and strong references – to those blocks.

So we’ve seen blocks be declared, assigned values, and passed like variables. We’ve also seen that they look like functions. Now we’re sending a block a message as if it were an object.

A heap-based block behaving like an object comes with some memory management issues:

What about variables that are used with the block?

A block typically uses other variables (both primitive and pointers to objects) within its code that were created outside of it. To make sure these external variables will be available for as long as the block needs them, the variables are captured by the block when the copy is made.

For primitive variables, this means the values are copied and stored as local variables within the block. For pointers, the block itself will keep a strong reference to any objects it references. That means that any objects referred to by the block are guaranteed to live at least as long as the block itself. (If you’ve been wondering about the difference between blocks and function pointers, it’s right here. Let’s see a function pointer do that!)

As an example, take a look at our VowelMovement program. The devowelizer block mentions two objects that were created outside of the block: newStrings (an array for storing the modified versions of strings) and string (the current string to be copied for modification). devowelizer will keep strong references to both of these objects, keeping them alive as long as the block itself exists.

Can these strong references lead to retain cycles/circular references?

You bet. The fix is the same: one of the references needs to become a weak reference. To do this, declare a __weak pointer outside the block and then reference this pointer within the block instead.

234

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