问题
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