What is the problem with the way I create and populate NSArray in Objective-C?

I use cocos2d to populate an NSMutable Array and then create an NSArray from this array. I do the following code 3 times in a row with different array names, and for the third time the Tools report leaks with every element that I add to the array.

The strange thing is that this is not EVERYONE creating and adding CCSprite, but the lines he complains about are different every time the application starts. What am I doing wrong? Is there a better way to do 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 looking at this. The first time I use tempSprite, I initialize it as follows:

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

I free tempSprite between each distribution because otherwise it is a leak. [tempNumberArray addObject: tempSprite] saves the sprite object.

+4
source share
1 answer

I'm not sure why you are seeing leaks. The code you posted is correct, although it is not necessary to set tempSprite to nil every time; you really only need to do this if it is likely that you will use a pointer to try to report this object after its release. However, this does not hurt anything.

The only improvement I can offer is to build an array construct 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]; 
+1
source

All Articles