加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 我如何在Objective C中创建和填充NSArray有什么

发布时间:2020-12-16 06:57:01 所属栏目:百科 来源:网络整理
导读:我使用cocos2d来填充NSMutable数组,然后从该数组创建一个NSArray.我连续3次使用不同的数组名称执行以下代码,第三次,Instruments报告了我添加到数组中的每个元素的泄漏. 奇怪的是,它不是每次创建和添加CCSprite,并且每次运行应用程序时它所抱怨的行都不同.我
我使用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]保留sprite对象.

解决方法

我不确定你为什么会看到泄漏.你发布的代码是正确的,虽然没有必要每次都将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];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读