0

我正在使用 cocos2d 编写代码。我想释放我分配的所有内存。我已经通过以下方式在 dealloc 方法中完成了它。
我发布的所有对象都在接口文件中声明,属性(分配)已设置并在实现文件中合成。
我使用 alloc 方法来创建它们

self.PlayerA = [[CCSprite alloc] initWithFile:@" PlayerImage_01.png"];


-(void)dealloc
{
 int count , i ;

 count = [self.PlayerA retainCount];
 for(i = 0; i < count; i++)
   [self.PlayerA release];

 count = [self.targetLayer retainCount];
 for(i = 0; i < count; i++)
   [self.targetLayer release];

  count = [self.playerGunSlowDrawSheet retainCount];
 for(i = 0; i < count; i++)
    [self.playerGunSlowDrawSheet release];

 count = [self.playerGunSlowDrawAnimation retainCount];
 for(i = 0; i < count; i++)
    [self.playerGunSlowDrawAnimation release];

 count = [self.numberFinishedTime retainCount];
 for(i = 0; i < count; i++)
    [self.numberFinishedTime release];

 count = [self.backGroundImage retainCount];
 for(i = 0; i < count; i++)
   [self.backGroundImage release];

 [[CCTextureCache sharedTextureCache] removeAllTextures];
 [[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFrames];

 [super dealloc];
 }

但我得到:程序接收信号:“EXC_BAD_ACCESS”。我调试它在 [super dealloc] 处显示错误;

我在内存管理方面完全错了吗?或者我错过了什么。谢谢你。

4

1 回答 1

1

是的,这不是释放对象的好方法。通过在您的 dealloc 方法中多次释放对象 A(如果它的保留计数 > 1),您可能会从可能正在使用对象的任何其他对象下方拉出地毯。

如果你拥有它,你应该只释放一次对象(假设你只保留一次对象或你自己分配它)。

有关“拥有”对象的更多信息,我建议您阅读 Apple 的内存管理编程指南:

http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

一旦你了解了 Objective-C 内存管理的基础知识,使用 XCode 的 Build 菜单中的 Build and Analyze 项应该有助于发现这样的问题

通常,dealloc 方法应如下所示:

-(void) dealloc
{
    [self.objectA release];
    [self.objectB release];

    [super dealloc];
}

编辑:要回答关于为什么获得 EXC_BAD_ACCESS 的原始问题,这里没有足够的信息来确定原因。一个可能的原因可能是您正在释放子类中的一个对象,该对象也在您的超类的 dealloc 方法中被释放。但这只是在黑暗中的一个镜头

于 2010-06-22T10:06:46.617 回答