Friday, 13 January 2012

Interesting example of 2 dimensional array in CCArray - to "alloc" or not?

I was reading Learn cocos2d Game Development with iOS 5 by Steffen Itterheim. There's something quite interesting in chapter 8 which I tried a few times but still don't quite get it.

There's this piece of code (Listing 8-7) which I will only list part of it here:

-(void) initEnemies
{
  enemies = [[CCArray alloc] initWithCapacity:EnemyType_MAX];

  for (int i = 0; i < EnemyType_MAX; i++)
  {
    .....


    CCArray* enemiesOfType = [CCArray arrayWithCapacity:capacity];
    [enemies addObject:enemiesOfType];
  }
}


-(void) dealloc
{
  [enemies release];
  [super dealloc];
}

The explanation is as below:

The interesting part here is that the CCArray* enemies itself contains more CCArray* objects, one per enemy type. It’s what’s called a two-dimensional array. The member variable enemies requires the use of alloc, because otherwise its memory would be freed after leaving the initEnemies method. In contrast, the CCArray* objects added to the enemies CCArray do not need to be created using alloc, because the enemies CCArray retains the objects added to it.


To make the whole thing clearer, the declaration of "enemies" is in the header file (Listing 8-6) as below:

#import "cocos2d.h"
@interface EnemyCache : CCNode
{

  CCArray* enemies;
}
@end

But I thought if "initEnemies" was called, then as long as the EnemyCache class doesn't get released, the member variable enemies should always exist isn't it? Confused... Might try to post it in Steffen's forum...

No comments:

Post a Comment