Tutorial :Cocos2d-iphone,not calling dealloc when replacing scene


This is a simplified version of the problem I'm facing now. I've made 2 empty CCScene 1 & 2 and added CCLayer 1 & 2 onto their respective scene. I also added an touches function to switch from scene 1 to scene 2 using CCDirector's replacescene.

However, dealloc was never called during the replace scene.

// scene & layer 2 are exactly the same as 1  @implementation MainScene        -(void)dealloc {       NSLog(@"scene dealloc");       [super dealloc];      }        -(id)init {       self = [super init];       if (self) {        layer = [[MainLayer alloc]init];        [self addChild:layer];        [layer release];        NSLog(@"test: %i", [layer retainCount]); //1       }     return self;  }    @implementation MainLayer    -(void)dealloc {   NSLog(@"layer dealloced");   [super dealloc];  }    -(id)init {   self = [super init];   if (self) {    self.isTouchEnabled = YES;              NSLog(@"test %i", [self retainCount]); //1   }   return self;  }    -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {   NSLog(@"test %i", [self retainCount]); //2 --> ????   [[CCDirector sharedDirector] replaceScene:[[SecScene alloc]init]];  }  

furthermore, the NSLog reported the retaincount of the layer to be 2 when I touch the screen. Is this even suppose to be happening? Can anyone probably tell me what I've done wrong or is it just my misunderstanding that retainCount needs to be 0 before dealloc is called?

This problem is causing my main game program to crash just by switch between various scenes/layers with just static sprites (and some minor actions) over and over again.


I'm not too knowledgeable about cocos2d's contract but shouldn't you release the SecScene you alloc in ccTouchesBeganon this line: [[CCDirector sharedDirector] replaceScene:[[SecScene alloc]init]]

I don't see any reason why replaceScene wouldn't retain, so now the SecScene has a retain count of two when it should have one.

More importantly, if you added MainScene in a similar way that would explain why its retain count is one higher than you'd like it to be, so it will never get deallocated.


Also, the dealloc gets only called rarely I found - so it is hard to test and get it invoked...

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »