August 2011
Intermediate to advanced
552 pages
23h 48m
English
So when do you need to copy a block? Make a copy whenever a block will outlive the scope it is defined in. In particular, these snippets are broken:
if (rand() % 1 == 0) {
blockPtr = ^{ NSLog (@"You are a winner!"); };
} else {
blockPtr = ^{ NSLog (@"Please try again!"); };
}
The braces for the branches of the if statement introduce a new scope, so the blocks are invalid afterwards.
blockPtr = ^{ NSLog (@"Help me"); };
return blockPtr;
Like returning the address of a local variable, returning a block that is still on the stack will cause problems ...
Read now
Unlock full access