Graphics Programs Reference
In-Depth Information
Variable Capturing
There is one special characteristic of blocks that makes them very useful: they
capture
vari-
ables.
A block, like a function, can use the arguments passed to it and can declare local variables.
Modify the block in
BNRAppDelegate.m
's
applica-
tion:didFinishLaunchingWithOptions:
so that it declares and uses a local
variable.
[executor setEquation:^int(int x, int y) {
int sum = x + y;
return x + y;
return sum;
}];
The variable
sum
is local to the block, so
sum
can be used inside this block. Both
x
and
y
are arguments of the block, so they, too, can be used inside this block.
A block can also use any variables that are visible within its
enclosing scope
. The enclosing
scope of a block is the scope of the method in which it is defined. Thus, a block has access
to all of the local variables of the method, arguments passed to the method, and instance
variables that belong to the object running the method. Change
applica-
tion:didFinishLaunchingWithOptions:
to declare a local variable and then
use that variable in the block.
BNRExecutor *executor = [[BNRExecutor alloc] init];
int multiplier = 3;
[executor setEquation:^int(int x, int y) {
int sum = x + y;
return sum;
return multiplier * sum;
}];
Build and run the application. The console will report the result of the equation as
21
.
When a block accesses a variable that is declared outside of it, the block is said to
capture
that variable. Thus, the value of
multiplier
is copied into the memory for the block
(
Figure 27.3
). Each time the block executes, that value will be used, regardless of what
happens to the original
multiplier
variable. (The original local variable will be des-
troyed as soon as
application:didFinishLaunchingWithOptions:
returns.)