【问题标题】:What is the problem with how I am creating and populating a NSArray in Objective C?我如何在 Objective C 中创建和填充 NSArray 有什么问题?
【发布时间】:2011-07-27 19:41:44
【问题描述】:

我正在使用 cocos2d 填充一个 NSMutable 数组,然后从该数组创建一个 NSArray。我使用不同的数组名称连续执行以下代码 3 次,第三次 Instruments 报告我添加到数组中的每个元素的泄漏。

奇怪的是,它不是在每次创建和添加 CCSprite 时,每次运行应用程序时它抱怨的行都不一样。我究竟做错了什么?有更好的方法吗?

这是我的代码:

NSMutableArray *tempNumberArray = [[NSMutableArray alloc] init];

tempSprite = [[CCSprite alloc] initWithSpriteFrameName:@"0.png"];
[tempNumberArray addObject:tempSprite];
[tempSprite release];
tempSprite = nil;


tempSprite = [[CCSprite alloc] initWithSpriteFrameName:@"0.png"];
[tempNumberArray addObject:tempSprite];
[tempSprite release];
tempSprite = nil;

tempSprite = [[CCSprite alloc] initWithSpriteFrameName:@"0.png"];
[tempNumberArray addObject:tempSprite];
[tempSprite release];
tempSprite = nil;

tempSprite = [[CCSprite alloc] initWithSpriteFrameName:@"0.png"];
[tempNumberArray addObject:tempSprite];
[tempSprite release]; 
tempSprite = nil;

self.numbersArray = [NSArray arrayWithArray:tempNumberArray];
[tempNumberArray release];
tempNumberArray = nil;

编辑:感谢您查看此内容。 我第一次使用 tempSprite 时,我将它初始化为:

CCSprite * tempSprite = [[CCSprite alloc] initWithSpriteFrameName:@"0.png"];
[tempNumberArray addObject:tempSprite];
[tempSprite release]; 
tempSprite = nil;

我在每次分配之间释放 tempSprite,否则会泄漏。 [tempNumberArray addObject:tempSprite] 保留精灵对象。

【问题讨论】:

  • tempSprite的初始化代码是什么?
  • 你为什么要发布你的 tempSprites?如果你释放了它们,它们就不会出现在你的数组中。
  • @Luke:数组保留了添加的对象。释放使用 alloc 创建的对象是正确的,以便在重用指针时不泄漏。
  • 这可能与[NSArray arrayWithArray:tempNumberArray] 创建数组的autoreleased copy 的事实有关吗? (再想一想,可能不会,因为numbersArray 属性设置器会保留它,对吧?)
  • 是的,self.numbersArray 设置器会保留它,正确的。

标签: objective-c cocos2d-iphone


【解决方案1】:

我不确定您为什么会看到泄漏。您发布的代码是正确的,尽管不必每次都将tempSprite 设置为nil;如果您有机会在释放对象后使用指针尝试向对象发送消息,那么您真的只需要这样做。但是,它不会伤害任何东西。

我可以建议的唯一改进是在循环中进行数组构造:

// You can also use an autoreleased mutable array, since you don't need it
// to stick around after construction.
NSMutableArray * tempNumbersArray = [NSMutableArray array];
int i;
for( i = 0; i < NUM_OF_SPRITES; i++ ){
    CCSprite * tempSprite = [[CCSprite alloc] initWithSpriteFrameName:@"0.png"];
    [tempNumbersArray addObject:tempSprite];
    [tempSprite release];
}

self.numbersArray = [NSArray arrayWithArray:tempNumbersArray];

【讨论】:

  • 感谢有关使用 for 循环清理代码的建议。这是有道理的,我想我会这样做!我将不得不在我的代码中的其他地方寻找我得到的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多