G'Day all,
This is an update on progress of adding blocks (closures) support to cocos2d. I'd like to gauge interest in this sub-project, by number of responses to this thread - just reply with +1.
Background
Closures / blocks are available using the fantastic PLBlocks framework created by Plausible Labs (Landon Fuller). It is a back port of Apple's own open-sourced code and therefore 100% compatible when Apple introduces their own official version to the iPhone SDK. I am about to start a project with cocos2d and having just released an update to C64 for iPhone using blocks, I can't go back to creating methods on classes to handle "callbacks" and therefore decided to add support to cocos2d.
Current progress
Since you must link with the PLBlocks.framework, I've created a duplicate static library of cocos2d (cocos2d-blocks) that specifically incorporates block support. If you don't care about setting up PLBlocks, you'd continue to use the cocos2d library. Also, I'm using the new compiler define, __BLOCKS__ to conditionally include block-specific APIs in existing cocos2d classes.
I've added a new CCInstantAction called CCCallBlock, which is used like:
id some = [CCCallBlock actionWithBlock:^{
[label setString:@"Called Block!"];
}];
There are no overloads like CCCallBlockN and CCCallBlockND, as you simply capture the data in the closure.
CCMenuItem's are almost done, which is also introduces a more succinct syntax:
// Font Item
CCMenuItem *item4 = [CCMenuItemFont itemFromString: @"I toggle enable items" block:^{
disabledItem.isEnabled = ~disabledItem.isEnabled;
}];
Finally, the difference in calling a block to a target/selector is huge. For a parameterless block (CCCallBlock), it is 5 ARM instructions, whereas I gave up after counting 800+ instructions for the traditional CCCallFunc. Now, this is not likely to have a huge impact on a running app, but it all adds up, so it is certainly a good thing!
Cheers,
Stu