如何解除分配 CCLayer

Posted

技术标签:

【中文标题】如何解除分配 CCLayer【英文标题】:How to deallocate a CCLayer 【发布时间】:2011-10-04 00:37:01 【问题描述】:

我正在使用 cocos2d 为 iphone 制作一个 box2d 应用程序。我正在尝试将我的 CCLayer 从 HelloWorldLayer 切换到 HomeScene,但我收到错误消息“线程 1:程序收到信号:“EXC_BAD_ACCESS”。”当我尝试在我的 HelloWorldLayer 的 dealloc 方法中调用 [super dealloc] 时,它给了我这个错误。请帮忙。这是我的 .h 和 .mm

@interface HelloWorldLayer : CCLayer

    b2World *world;
    Cannon *cannon1;
    Cannon *cannon2;
    Cannonball *cannonball1;
    Cannonball *cannonball2;
    float theMass;
    float theMass2;
    CCSprite *sunBack;
    b2Vec2 cannon1Pos;
    b2Vec2 cannon2Pos;
    CCMenuItemSprite *pauseBut;
    CCMenuItemSprite *playBut;
    CCMenu *pauseMenu;

@property(nonatomic)b2Vec2 cannon1Pos;
@property(nonatomic)b2Vec2 cannon2Pos;

@property(nonatomic, retain)CCSprite *sunBack;
@property(nonatomic, retain)Cannon *cannon1;
@property(nonatomic, retain)Cannon *cannon2;
@property(nonatomic, retain)Cannonball *cannonball1;
@property(nonatomic, retain)Cannonball *cannonball2;
@property(nonatomic, retain)CCMenu *pauseMenu;

// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;
+(HelloWorldLayer *) sharedLayer;
-(void)createMonkeys;
-(void)restartGame;
-(void)playGame;
-(void)pauseGame;
-(CCSpriteBatchNode*)getSpriteBatch;
-(void)goToHome;

@end

这是我释放的 .mm

// on "dealloc" you need to release all your retained objects
- (void) dealloc

    // in case you have something to dealloc, do it in this method
    delete world;
    world = NULL;
    [[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
    [cannon1 removeFromParentAndCleanup:YES];
    [cannon2 removeFromParentAndCleanup:YES];
    [cannonball1 removeFromParentAndCleanup:YES];
    [cannonball2 removeFromParentAndCleanup:YES];

    // don't forget to call "super dealloc"
    [super dealloc];

【问题讨论】:

你在你的图层上调用 release 吗?许多 Cocos 对象几乎默认为 autorelase,所以如果你为你的层调用说 removeChild,我相信这应该足以隐式释放它。 【参考方案1】:

你可以试试这个代替你用过的dealloc

-(void) dealloc

delete world;
world = NULL;
cannon1 = NULL;
cannon2 = NULL;
cannonball1 = NULL;
cannonball2 = NULL;
[super dealloc];

【讨论】:

以上是关于如何解除分配 CCLayer的主要内容,如果未能解决你的问题,请参考以下文章

如何解除分配 CCLayer

删除、释放还是解除分配?

如何从 C# .NET 强制解除分配 COM 服务器对象

许多固定长度的最快分配和解除分配?

C:指向结构指针数组的指针(分配/解除分配问题)

根据标记和当前电源状态解除分配 Azure VMSS