Game Development Reference
In-Depth Information
CCMenuItemToggle* item8 = [CCMenuItemToggle itemWithItems:items
block:toggleBlock];
Effectively you have one block that handles three menu items. And because the mes-
sage string has changed before item8 , this particular menu item will print out a differ-
ent string every time you toggle it.
One issue when you start working with blocks is how the implementation and variable
declaration differ in subtle but important ways. In the implementation (right-hand side
of the equals symbol) you specify the return type following the caret symbol. However,
in the variable declaration (left-hand side of the equation), the return type comes first
and is never optional. You always have to specify void even if you can omit it on the
right-hand side—another reason to always use the return type on the right-hand side as
well.
What's more, the variable's name follows the caret symbol, and you have to write both
in brackets to avoid compiler errors. Compare the variable declaration on the left-hand
side with the block implementation on the right-hand side:
void (^toggleBlock)(id sender) = ^void(id sender) { /* block code here */ };
These small but subtle differences regarding declaration and implementation are prob-
ably what's most off-putting about the block syntax. But once you've seen several ex-
ample uses, you get used to it, and eventually it becomes second nature. Note that once
It's declared as a variable, you can pass the block variable around and you can even call
it just as you'd call a C function:
toggleBlock(nil);
Tip In the Essentials project I've added a method named -(void) moreB-
locksExamples that contains many examples of how to write blocks.
There's also an example using typedef and a preprocessor macro to allow you
to write blocks with less syntactic horror. This example declares a block vari-
able whose declaration and implementation were given a readable name: Neg-
ateBlock Negate = NegateBlockImp{ return !input; };
CCLOG(@"Negate returned: %@", Negate(YES) ? @"YES" :
@"NO");
Search Nedrilad ::




Custom Search