Game Development Reference
In-Depth Information
One thing you may have noticed is that the block doesn't declare a return type. For
void and int parameters, this is optional because the compiler assumes that the re-
turn type is void if no return statement is used inside the block. And if there's a
return statement returning a value, it defaults to int . Because this leads to compiler
errors when you want to return a different value than int , I find it good practice to
specify the return type even if you don't have to. The return type always follows the
caret symbol:
^void(id sender) {
// your code here . . .
Now you're probably wondering why you'd want to bother with syntactically odd
blocks when you can just use target and selector instead? For one, it allows you to
write the menu item handling code right where you define the menu item. Moreover,
the block has access to local variables. In this example, the message NSString can be
used within the block:
NSString* message = @"some kind of string";
NSArray* items = [NSArray arrayWithObjects:toggleBlockOn, toggleBlockOff, nil];
CCMenuItemToggle* item4 = [CCMenuItemToggle itemWithItems:items
block:^void(id sender) {
CCLOG(@"message is:%@", message);
What's more, you can re-use the same block for multiple menu items by assigning the
block to a variable. For clarity, I omit the NSArray* items declarations from this
NSString* message = @"some kind of string";
void (^toggleBlock)(id sender) = ^void(id sender) {
CCLOG(@"message is: %@ ", message);
CCMenuItemToggle* item6 = [CCMenuItemToggle itemWithItems:items
CCMenuItemToggle* item7 = [CCMenuItemToggle itemWithItems:items
message = @"a different string";
Search Nedrilad ::

Custom Search