开发者

Cocos2d: Should I use only (id)init for initializing, or can I use (void)onEnter for late allocation?

As learning Cocos2d, I've found - (void)onEnter, - (void)onExit, can be used like their counterparts, - (void)viewDidLoad, - (void)viewDidUnload of iOS UIKit.

I do aware they are not technically good replacement for the original - (id)init, and I often see instructive texts for learning Cocos2d only use - (id)init method for 开发者_Python百科all it's properties and variables.

However, if I use - (void)onEnter for allocation and initialization, I can reference self.parent for a little more cleaner code.

Is it safe to assume I can keep using - (void)onEnter for allocating and initializing without worrying if it's right way to develop using Cocos2d framework?


Assuming that you are careful about your initializations and memory management, this sounds like a perfectly reasonable way to handle your code but as you mention, it's not standard so please beware of some pitfalls.

The -(void) onEnter and -(void) onExit methods are actually more like -(void) viewWillAppear and -(void) viewWillDisappear than -(void) viewDidLoad and -(void) viewDidUnload

Be aware of:

  • onEnter is also called recursively on all of your node's children.
  • onEnter may be called several times depending on how you handle your scenes whereas init would only be called once. Be careful your objects don't leak by accidentally allocating them more than once.


It's doable, but a bad approach. onEnter is called when the CCNode is added to another CCNode, not when it or its parent is added to the screen. onEnter and onEnterTransitionIsFinished is meant to represent that the CCNode is loaded and ready to go. And unless you specifically keep your CCNodes outside of another CCNode (bad form), onEnter will be called immediately in the after your init. So your supposed lazy allocation is moot.

More importantly, you should be loading as much cacheable data (textures and such) at the start of your CCScene anyway, to prevent in-scene hiccups such as lazy allocation of large, and therefore, cacheable data. And if you've correctly done all that heavy lifting at the start of your scene, waiting to set some flags and number variables isn't going to do you any good. And doing so in a method that's meant for other things is even less helpful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜