views:

296

answers:

2

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.

+1  A: 

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.

anq
A: 

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

in that case you are very likely leaking memory by not matching alloc/release ... it's not the fault of the dealloc method, it's what, when and where you alloc/retain/release that's causing dealloc not to be called
GamingHorror