Graphics Programs Reference
In-Depth Information
Basics of Using Blocks
Say you wanted an object that could take two numbers, add them together, and then return
the result. You could probably write that pretty easily. But what if you now wanted that ob-
ject to perform subtraction? Then multiplication? Division? You'd end up writing a number
of methods for this object.
Instead of writing these methods, we can give this object an instance variable that points at
a block. When we want to swap out the operation this object uses, we can construct a block
literal that performs the appropriate operation. When the object is asked to compute the res-
ult, it executes the operation in the block.
Create a new
NSObject
subclass for
Blocky
and name it
BNRExecutor
. In
BNREx-
ecutor.h
, add an instance variable and two methods to the
BNRExecutor
class.
@interface BNRExecutor : NSObject
{
int (^equation)(int, int);
}
- (void)setEquation:(int (^)(int, int))block;
- (int)computeWithValue:(int)value1 andValue:(int)value2;
@end
The
setEquation:
method takes a block as an argument. Notice the syntax for declar-
ing that a method takes a block argument. The argument has nearly the same format as a
block variable. The only difference is the argument name (
block
) is separated from the
argument's type. Instead of following the caret, the argument name comes after the paren-
theses that declare the argument type (just like any other method argument).
Figure 27.2 BNRExecutor and its block
What do these methods do? Sending the message
setEquation:
to an instance of