Graphics Programs Reference
In-Depth Information
For the More Curious: The __block Modifier, Abbreviated
Syntax, and Memory
Blocks have a few more options than we've talked about in this chapter. First, when alloc-
ating blocks we have always put the return type in the block signature:
^ returnType (...) {
}
However, this isn't necessary. The compiler can figure out the return type based on the re-
turn statement in the block.
For example, these are all valid blocks and assignments:
int (^block)(void) = ^(void) {
return 10;
};
NSString * (^block)(void) = ^(void) {
return [NSString stringWithString:@"Hey"];
};
void (^block)(void) = ^(void) {
NSLog(@"Not gonna return anything...");
};
Also, if a block doesn't take arguments, you don't need to include the argument list in the
block literal. So, you could write a block and its assignment like this:
void (^block)(void) = ^{
NSLog(@"I'm a silly block.");
};
The return type and empty argument list can only be omitted from the block literal. A block
variable must have all of the information about the block it points to.
Earlier in this chapter, you saw how a block captured a variable by copying its value into
its own memory. Subsequent changes to that variable didn't affect the block's copy. One
thing we did not mention was that this captured variable cannot be changed within the
block. For example, this is illegal:
int five = 5;
void (^block)(void) = ^{
five = 6; // This line causes an error
};
Search WWH ::




Custom Search