Graphics Programs Reference
In-Depth Information
Defining block literals
Of course, we know that a variable itself doesn't contain much information: it just stores a
value. For example, the value of an
int
variable is a numerical value, like
5
. The value
of an
NSString *
variable will be an address of an instance of
NSString
.
The same holds true for a block variable. The variable stores a value, and the value will be
the address of a block. A block is an object, so it needs to be allocated. To allocate a
block, you specify the code that makes up the block. The syntax for creating a block looks
like this:
^int(int x, int y) {
return x + y;
};
The definition of a block is called a
block literal
. Notice the form of a block literal: a
caret, the return type, and then parentheses that contain the arguments. In this case, this
block takes two
int
arguments and returns their sum.
Typically, you create a block and immediately assign a variable to point to it. (You can
also create a block and then pass it directly to a method. We'll talk more about this option
later in the chapter.) In
BNRAppDelegate.m
, update
applica-
tion:didFinishLaunchingWithOptions:
to assign
adder
to point to a block
object.
- (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;
};
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
This code is just a combination of what you know: it creates a block variable named
ad-
der
that points to a newly allocated block that returns the sum of the two arguments.
Build the application to check for syntax errors. You should still only see the warning that
adder
is unused.
Here are some more examples of blocks and variables that point to them:
void (^foo)(void) = ^void(void) {