Graphics Programs Reference
In-Depth Information
int a = 2;
int b = 5
int val = [executor computeWithValue:a andValue:b];
Or we could bypass creating the variables and just pass literal values:
int val = [executor computeWithValue:2 andValue:5];
The same can be done when passing a block to a method. Instead of allocating a block,
setting a variable to point at it, and then passing that variable to a method, you can just
pass a block literal as the argument. (This is what we did back in Chapter 13 when we
passed a block to be executed when the modal view controller was dismissed.) In ap-
plication:didFinishLaunchingWithOptions: , modify the code so that the
variable adder is no longer used.
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
int (^adder)(int, int) = ^int(int x, int y) {
return x + y;
};
BNRExecutor *executor = [[BNRExecutor alloc] init];
[executor setEquation:adder];
[executor setEquation:^int(int x, int y) {
return x + y;
}];
NSLog(@"%d", [executor computeWithValue:2 andValue:5]);
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Build and run the application. You will see the same output, but your code is much more
succinct. The block is allocated and immediately passed to the BNRExecutor , which
sets its equation instance variable to point at it. Now you can see exactly what the
block does (what code it contains) right where it's called rather than having to find the
definition back where the variable is declared. This makes for much less clutter in your
code files.
Like any other instance variable, a block can be exposed as a property of a class. In
BNRExecutor.h , declare a property for the equation block to replace the setter
method. Since you will be synthesizing this property, you no longer need the instance
variable explicitly declared either.
@interface BNRExecutor : NSObject
 
Search WWH ::




Custom Search