views:

441

answers:

1

I tried storing some CCSprites in a NSMutableArray, but the game crashed immediately, I'm guessing it's a memory problem, and I'm also guessing that CCSprites are autorelease objects?

So, how would I store multiple CCSprites in a NSMutableArray?

The purpose I wanna do this is store for example all enemies in an array, and then loop through them in my timestep function and update their positions and whatnot.

What I tried to do:

NSMutableArray *enemies = [NSMutableArray array];
[enemies addObject: [CCSprite spriteWithFile: @"hello.png"]];

It crashes when I try to reach the sprite using -objectAtIndex:

+2  A: 

The array is autoreleased. If you try to access it later in another context, it probably already died. So you either retain it or don't use the convenience array method, but [[NSMutableArray alloc] init] explicitly.

Or store it in a retained property (be sure to use the setter method in that case, i.e. self.ivar = enemies;

Whichever way you go, be cautious not to "over-retain" your array, i.e. using alloc/init and the retaining setter, or your array will never get freed again (more correctly it will only get freed with a "buggy" double release).

Eiko