iphone - Cocos2d-iphone,替换场景时不调用dealloc

标签 iphone memory cocos2d-iphone

这是我现在面临的问题的简化版本。 我制作了 2 个空的 CCScene 1 和 2,并将 CCLayer 1 和 2 添加到各自的场景中。 我还添加了一个触摸功能,使用 CCDirector 的 Replacescene 从场景 1 切换到场景 2。

但是,在替换场景期间从未调用 dealloc。

// 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]];
}

此外,当我触摸屏幕时,NSLog 报告该层的保留计数为 2。这真的会发生吗?谁能告诉我我做错了什么,还是只是我的误解,在调用 dealloc 之前,retainCount 需要为 0?

这个问题导致我的主游戏程序仅通过一次又一次地在仅具有静态 Sprite (和一些小 Action )的各种场景/图层之间切换而崩溃。

最佳答案

我对cocos2d的合约不太了解,但是你不应该释放你在ccTouchesBegan中分配的SecScene在这一行:[[CCDirector共享Director]替换场景:[[SecScene alloc]init]]

我看不出 replaceScene 不保留的任何原因,所以现在 SecScene 的保留计数为 2,而它应该有 1。

更重要的是,如果您以类似的方式添加 MainScene ,就可以解释为什么它的保留计数比您希望的高 1,因此它永远不会被释放。

关于iphone - Cocos2d-iphone,替换场景时不调用dealloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3146900/

相关文章:

ios - 当 Sprite 到达该位置时代码崩溃

iphone - 如何在 iphone 中创建具有 Marquee Effect 的动态多个 uiview

iphone - iCarousel 在用户选择的索引处停止

objective-c - 图像的圆角

c++ - C/C++ 字符串内存泄漏?

python - 为什么单个 10x10x3 的 Conv2d 占用 850mb gpu

iphone - 选择视频并播放时出现问题

memory - 什么是 idr_alloc()

iphone - 如何使 iphone 和 iphone4-retina 兼容的应用程序(在 cocos2d 中完成)轻松适应 ipad?

IOS图像内存使用