开发者

What is the problem with how I am creating and populating a NSArray in Objective C?

I am using cocos2d to populate a NSMutable Array, then creating an NSArray from that array. I do the following code 3 times in a 开发者_运维百科row with different array names, and on the third time Instruments is reporting leaks with each element I add to the array.

The weird thing is, its not on EVERY creation and addition of a CCSprite, and the lines that it complains about are different every time I run the app. What am I doing wrong? Is there a better way of doing this?

Here is my code:

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;

Edit: Thanks for taking a look at this. The first time I use tempSprite I initialize it like:

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

I release tempSprite between each allocation because it would be a leak otherwise. [tempNumberArray addObject:tempSprite] retains the sprite object.


I'm not sure why you're seeing leaks. The code you've posted is correct, although it's not necessary to set tempSprite to nil every time; you really only need to do this if there is a chance you will use the pointer to try to message the object after releasing it. It doesn't hurt anything, however.

The only improvement I can suggest is to do the array construction in a loop:

// 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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜