Game Development Reference
In-Depth Information
CCLOG(@"item 4 touched with block: %@ - selected index: %i", sender, index);
}];
Now look at the same block again, but this time you make use of the fact that the block
has access to variables in the scope where the block is declared. In this case, instead of
using the sender , which turns out to be the CCMenuItemToggle , you can simply
refer to the item4 variable directly. This is called capturing state . Even if you as-
signed a different object to item4 directly after where the block is declared, the block
will still refer to the object that was stored in the item4 variable at the time the block
was created.
NSArray* items = [NSArray arrayWithObjects:toggleBlockOn, toggleBlockOff, nil];
CCMenuItemToggle* item4 = [CCMenuItemToggle itemWithItems:items
block:^(id sender) {
int index = item4.selectedIndex;
CCLOG(@"item 4 touched with block: %@ - selected index: %i", item4, index);
}];
item4 = nil;//inside the block item4 will still be the menu item object
This particular menu item initializer takes a block as a parameter. Unfortunately,
cocos2d doesn't document which signature the block function should have, so you'll
have to dig up this information from any cocos2d method that accepts a block. Consult-
ing with the CCMenuItem.m file where CCMenuItemToggle is implemented, you
can see the block returns void (no return value) and passes an id sender object to
the function:
block:(void(^)(id sender))block
Therefore, the block you need to implement needs to have the following signature:
^(id sender) {
// your code here . . .
}
By now you'll have noticed the oddly placed caret (^) symbol. That tells the compiler
that the following code is a block. Following the caret, you first declare the parameter
list in brackets, and following that is your code in curly brackets. So that's pretty
straightforward.
Search Nedrilad ::




Custom Search