Graphics Programs Reference
In-Depth Information
Figure 27.3 Captured variables are copied into the block
In fact, you can change the multiplier variable after the block is created, and it still
won't change the multiplier within the block. When a block copies the value of a variable,
it doesn't care what happens to the original variable afterwards. In BNRAppDeleg-
ate.m , change the value of multiplier after creating the block.
int multiplier = 3;
[executor setEquation:^int(int x, int y) {
int sum = x + y;
return multiplier * sum;
}];
multiplier = 100;
Build and run the application. Notice that the console reports the same output from the
equation, even though the block is called after multiplier is changed. You don't need
to do anything special to capture a variable ? you simply must use it somewhere in the
block.
This behavior is unique to blocks. The only way you can get values to functions is to pass
them as arguments, and the only way you can get values to methods is to pass them as ar-
guments or have them stored in an instance variable. A block can take arguments and cap-
ture variables from their enclosing scope.
This is an important point: the values of the captured variables remain the same every
time the block is called, but the values of its arguments can change each time it is called.
In this case, that means you can change the two values that are added together each time
you call the block, but the multiplier will always remain the same.
 
Search WWH ::




Custom Search