【发布时间】:2010-09-08 14:44:29
【问题描述】:
由于某种原因,当我释放 NSArray 时,我得到了 EXC_BAD_ACCESS 异常。这是实现:
-(void) loadAllAlphabets
{
NSBundle *bundle = [NSBundle mainBundle];
NSArray *imagesPath = [[NSArray alloc] init];
imagesPath = [bundle pathsForResourcesOfType:@"png" inDirectory:@"Images"];
alphabets = [[NSMutableArray alloc] init];
NSString *fileName = [[NSString alloc] init];
for(int i=0; i<= imagesPath.count -1 ; i++)
{
fileName = [[imagesPath objectAtIndex:i] lastPathComponent];
CCSprite *sprite = [CCSprite spriteWithFile:fileName];
sprite.userData = [[fileName stringByDeletingPathExtension] uppercaseString];
[alphabets addObject:sprite];
}
// release fileName
[fileName release];
fileName = nil;
[imagesPath release]; // this causes the application to crash with EXC_BAD_ACCESS
// imagesPath = nil;
}
更新 1:
所以,问题在于,虽然我负责释放 imagesPath 对象,因为我使用了 alloc,但当 pathForResourcesOfType 返回一个自动释放对象时,它很快就变得无关紧要了。 这意味着我不应该手动释放 imagesPath 对象。
应使用以下行:
NSArray *imagesPath = [bundle pathsForResourcesOfType:@"png" inDirectory:@"Images"];
更新 2:
另一个与这篇文章相关的问题。在下面的代码中,我手动初始化了一个新的 NSMutableArray。
alphabets = [[NSMutableArray alloc] init];
稍后我将 CCSprite(Cocos2d 对象)插入到字母数组中。 CCSprite 是自动释放对象。我还需要手动释放字母吗?因为,一段时间后,所有对象都被释放并且内存将被返回,但是字母 NSMutable 数组中会留下什么?
【问题讨论】:
-
当您将 imagesPath 重新分配给 pathsForResourcesOfType: 调用时会发生泄漏,因为您已经分配了并且 i
标签: iphone