Graphics Programs Reference
In-Depth Information
Sometimes, you do want to modify a variable inside a block. A typical example is some
sort of counter variable that should go up each time you execute a block. If you want this
behavior, you have to specify the variable as mutable within the block by decorating it
with
__block
:
__block int counter = 0;
void (^block)(void) = ^{
counter++;
NSLog(@"Counter now at %d", counter);
};
block(); // prints 1
block(); // prints 2
When a variable is decorated with
__block
, it actually lives in a special spot in memory:
it is not a local stack variable, nor is it stored inside the block itself (
Figure 27.5
)
.
Figure 27.5 Shared Memory for __block variables
This is important because it means more than one block can modify that variable:
__block int counter = 0;
void (^plusOne)(void) = ^{
counter++;
NSLog(@"Counter now at %d", counter);
};
void (^plusTwo)(void) = ^{