开发者

Cocos2D - NSMutableArray of CCSprites

开发者 https://www.devze.com 2023-01-02 10:05 出处:网络
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?

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 -objectAtI开发者_如何学Gondex:


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).

0

精彩评论

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