Graphics Programs Reference
In-Depth Information
};
// Since the block literal calls its argument x, it doesn't matter
// what the block variable calls it.
void (^foo)(int y) = ^void(int x) {
NSLog(@"%d", x);
};
This block and block variable pairing, on the other hand, would cause an error.
// This is a compiler error because the block calls its argument x, but it ref-
erences
// the variable y, which doesn't exist
void (^foo)(int y) = ^void(int x) {
NSLog(@"%d", y);
};
Furthermore, the type of a block variable must match the type of the block it points to. If
not, the compiler will give you an error. Here are some examples of erroneous block and
block variable pairings:
// This is a compiler error because the return types differ (void vs. int)
void (^block)(void) = ^int(void) {
return 0;
};
// This is a compiler error because the argument types differ (int vs. float)
void (^block)(int) = ^void(float x) {
NSLog(@"%f", x);
};
Also, notice that blocks are created inside methods (or functions). This is different than
the definition of methods and functions, which occupy their own area in an implementa-
tion file. While it is possible to create a block outside of a method or function, there is
rarely any reason to do so.
Finally, functions and methods can be called anywhere as long as you have imported the
file that contains their declaration. A block, being an object, can only be used if you have
a variable that points to it. Therefore, if you create a block in a method, any other method
that wishes to execute that block must be passed a pointer to that block. You will test this
behavior in the next section.
Search WWH ::




Custom Search