Cocos2D scene memory management

青春壹個敷衍的年華 提交于 2019-12-10 11:39:01

问题


I have a question about Cocos2D. I have 2 scenes in my game both have a lot of sprites on the scene. What happened when I replace the one scene and load another? Are all sprites removed automatically or it is taking memories and will be release when I release in dealloc of the scene?

I am unable to understand of this thing how the memory manage in this condition, so can any one explain me that thing and one thing more is this is important for us to make the sprite retain when we load it on the scene.


回答1:


The moment you call replaceScene both scenes will exist in memory for a short time period! If you use a CCSceneTransition then both scenes will be in memory for the duration of the transition.

The flow is as follows:

  • scene A is running
  • call CCDirector replaceScene with sceneB
  • scene B is initialized, may load sprites etc
  • scene A is deallocated and memory released

You can implement the -(void) cleanup method in a scene to remove most of its content before changing the scene, and you may want to defer loading new content to the -(void) onEnter { [super onEnter]; } method.

Personally I find the better approach in this scenario a "loading" scene, a scene that comes in between the two scenes (it may not even be active for more than a few milliseconds). This gives the first scene time to be deallocated before the next scene is initialized.




回答2:


All sprites are released after the new scene is loaded in the memory..unless you have retained the sprites.




回答3:


if what you're doing are

CCSprite* sprite = [CCSprite spriteWithFile:@"test.png"];

no retaining or anything fancy, when you switch / transition the scene, all the children of this scene (in this example, sprite, will automatically released. You don't take ownership of the object.

But if you let say if you take the ownership of the object, for example:

hero = [[CCSprite spriteWithFile:@"hero.png"] retain];
// or
hero = [[CCSprite alloc] initWithFile:@"hero.png"];

then you'll need to release it in your dealloc



来源:https://stackoverflow.com/questions/8989189/cocos2d-scene-memory-management

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!