ZhouWeikuan / cocos2d

cocos2d for android, based on cocos2d-android-0.82, and now ported from cocos2d-iphone 0.99.4. The googlecode address is here: http://code.google.com/p/cocos2d-android-1/ . There are several demos to watch.
610 stars 291 forks source link

memory allocation when using CCSprite array #15

Closed BMR11 closed 13 years ago

BMR11 commented 13 years ago

Hi everyone, I have some confusion related to memory allocation. Suppose I need an array of sprites. I will declare them as CCSprite mySprites = new CCSprite[MAX_SPRITES]; and while creating i will create them and add to current layer like: for(int i=0;i<MAXSPRITES;i++) { mySprites[i] = CCSprite.sprite("image"+i+".png"); this.addChild(mySprites[i]); }

Now sprites are added to layer but we need to access them while game flow so we will use mySprites; So my question is when we do this.removeAllChildren(true); for this layer, will it remove all children and also mySprites sprites? Or do we need to do something like this for(int i=0;i<MAX_SPRITES;i++) { mySprites[i] = null; }

In my game I think memory is leaking if there is simillar case.

We can also use tags to retrive sprites instead of using "CCSprite mySprites = new CCSprite[MAX_SPRITES];".

Please can you tell me what is the solution for this?

Thanks.

dustinanon commented 13 years ago

This is a Java issue, not a cocos2d issue. You have references in both your mySprites array and the cocos2d Layer, so even though you run removeAllChildren(true), you still have a hard reference in your mySprites array, so the garbage collector does not clean them up.

There is no need to iterate the array and null out each entry, a simple mySprites = null will suffice (relative reference breaking).

The other thing you can do is just reinitialize your array in order to prepare for your new Sprites. mySprites = new CCSprite[MAXSPRITES].

If the problem still persists after doing this, then post the issue again and we can look into that.

ZhouWeikuan commented 13 years ago

agree, the issue should be closed