Storing pointers to objects in array in Objective c

南楼画角 提交于 2019-12-13 06:17:35

问题


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?

回答1:


  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.




回答2:


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.



来源:https://stackoverflow.com/questions/11401368/storing-pointers-to-objects-in-array-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!