Graphics Programs Reference
In-Depth Information
NSLog(@"I'm a lonely block.");
};
void (^jump)(Hurdle *) = ^void(Hurdle *hurdle) {
[hurdle comeCrashingDown];
};
int (^doubler)(int) = ^int(int x) {
return x * 2;
};
Executing blocks
Once a block variable points to a block, you can call the variable like a C function to ex-
ecute the code in the block that is pointed to. Update applica-
tion:didFinishLaunchingWithOptions: to execute the adder block and
print out its return value.
- (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;
};
int sum = adder(2, 5);
NSLog(@"%d", sum);
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Build and run this application. You will see the standard warning about applications not
having a root view controller. Ignore this and look for the result of executing this block: 7 .
More notes about blocks
There are a few things to mention here. First, notice that a block variable is not required to
declare argument names. The block literal will declare the names of its arguments because
it is the one that uses them. A block variable can declare the names of its arguments, but
those names are irrelevant in the block itself. So, here are some legal block and block
variable pairings:
void (^foo)(int) = ^void(int x) {
NSLog(@"%d", x);
Search WWH ::




Custom Search