gpt4 book ai didi

ios - Cocos2d 和 iOS : how to deal with dealloc methods of static CCScene

转载 作者:行者123 更新时间:2023-11-29 04:25:26 25 4
gpt4 key购买 nike

我正在使用 CCScene 的 GameScene 子类的一些静态实例。从 GameScene 调用

[[CCDirector sharedDirector] replaceScene:[MainMenuScene scene]]; 

不会触发GameScene的dealloc方法。

一旦我再次加载场景(并且创建了一个新的 GameScene),就会调用该方法:

+(id) sceneWithId:(int)sceneId
{
CCScene* scene = [CCScene node];
GameScene* gameScene = [[self alloc] initWithId:sceneId];
[scene addChild:gameScene z:0 tag:GameSceneLayerTagGame];
return scene;
}

-(id) initWithId:(int)sceneId
{
CCLOG(@"scene With id");
if ((self = [super init]))
{
instanceOfGameScene = self;
//ONLY NOW the previous object becomes unreferenced and the memory management system is allowed to deallocate it

我想了解是否有一种方法可以强制在每次替换(静态)场景时调用 dealloc 方法,而不仅仅是在内存被“释放”时调用。

或者,如果我应该编写一些清理方法来停止正在进行的进程,而我不想影响 MainMenuScene (例如,我在 GameScene 的 dealloc 方法中放置了一个停止背景音乐方法调用,但也将背景音乐音乐位于静态类中 - 并且不会作为子项添加到 GameScene - 然后它会在 MainMenuScene 中继续播放)。

因此,我的快速修复建议是执行以下操作:

    [self stopAllStuffInOtherStaticClassesThatAreRelatedOnlyToGameScene];
[[CCDirector sharedDirector] replaceScene:[MainMenuScene scene]];

这是一个好方法吗?

编辑:什么时候在 dealloc 方法中添加此代码是明智的?

  [self removeAllChildrenWithCleanup:TRUE];

最佳答案

我闻到了不好的做法。永远不要保留节点的静态实例。特别是不在场景层次结构之外。它只是破坏了 cocos2d 处理内存管理的方式。

如果您需要保留状态,请将此状态保存到单独的类中,但在更改场景时一定要让场景消失。然后在场景再次启动时恢复状态。

您不能强制执行 dealloc 方法。想要这样做是代码味道的标志。不过,您可以重写 -(void) cleanup 方法,以便在 dealloc 之前以及将节点作为子节点删除之后运行去初始化代码。

EDIT: when is sensible to add this code in the dealloc method?

[self removeAllChildrenWithCleanup:TRUE];

从来没有。曾经。

同样,如果您发现需要这样做,则说明某个地方存在严重错误。此时 Cocos2D 已经删除了子节点。事实上,它是在 cleanup 方法期间执行此操作的,导致 cocos2d 不删除节点子节点的一种方法是当您覆盖 cleanup 且不调用 [super cleanup] 时。

或者也许当您将其保留为静态实例时,它永远不会真正调用清理方法。更糟糕的是继续运行计划的更新和操作。

关于ios - Cocos2d 和 iOS : how to deal with dealloc methods of static CCScene ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12395242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com