Phil
Phil

Reputation: 3045

Storing pointers to objects in array in Objective c

I'm using this code to create some objects and then store them in an array

for (int iy=0; iy<5; iy++) {
        for (int ix=0; ix<5; ix++) {

            TerrainHex *myObject = [[TerrainHex alloc] initWithName:(@"grassHex instance 10000") width:mGameWidth height:mGameHeight indexX:ix indexY:iy];
            myObject.myImage.y += 100;

            [TerrainHexArray addObject:myObject];

            [self addChild:(id)myObject.myImage];
        }
    }
    NSLog(@"%lu", sizeof(TerrainHexArray));

Few questions.

  1. The log is only displaying 4, which makes no sense, shouldn't it be 5x5, i'e 25?
  2. Am I creating 25 seperate object pointers there or just re-using the same one over and over? I'm trying to save all 25 pointers into an array.
  3. I'm using ARC but do I have to release anything there?

Upvotes: 0

Views: 402

Answers (2)

Andrew Madsen
Andrew Madsen

Reputation: 21383

  1. sizeof() tells you the size in bytes of the variable TerrainHexArray which is (presumably) a pointer to an NSMutableArray. Assuming a 32-bit system, pointers are 32 bits which is 4 bytes. You should be using [TerrainHexArray count] instead. That's a method that returns the number of objects in the array.

  2. You're creating 25 object instances, not the same one over and over. myObject is just a variable holding a pointer to a given object. Changing it by assignment doesn't obliterate the object it pointed to before (though ARC takes care of releasing it).

  3. No, ARC takes care of memory management for you.

One nitpick: Assuming TerrainHexArray is an instance of NSArray, you shouldn't capitalize the first letter. This isn't a requirement of the language, but it is convention to capitalize class names, but use a lower case first letter for variable names. terrainHexArray would be more appropriate and make the code more readable.

Upvotes: 2

MByD
MByD

Reputation: 137432

The log is only displaying 4, which makes no sense, shouldn't it be 5x5, i'e 20?

use [TerrainHexArray count] to get the amount of objects in the array. sizeof(TerrainHexArray) gives you the size of an id *, which is 4 bytes in your system.

Am I creating 20 seperate object pointers there or just re-using the same one over and over? I'm trying to save all 20 pointers into an array.

You are creating 25 objects

I'm using ARC but do I have to release anything there?

No.

Upvotes: 2

Related Questions