这是我现在面临的问题的简化版本。 我制作了 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/