在Objective c中存储指向数组中对象的指针 [英] Storing pointers to objects in array in Objective c

查看:43
本文介绍了在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));

几个问题.

  1. 日志只显示 4,这没有意义,不应该是5x5,即 25?
  2. 我是在那里创建 25 个单独的对象指针还是只是一遍又一遍地重复使用同一个?我试图保存所有 25指向数组的指针.
  3. 我正在使用 ARC,但我是否必须发布有什么吗?

推荐答案

  1. sizeof() 告诉你变量 TerrainHexArray 的字节大小,它(大概)是一个指向 NSMutableArray 的指针.假设一个 32 位系统,指针是 32 位,也就是 4 个字节.您应该使用 [TerrainHexArray count] 代替.这是一个返回数组中对象数量的方法.

  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.

您正在创建 25 个对象实例,而不是一遍又一遍地创建相同的实例.myObject 只是一个变量,持有一个指向给定对象的指针.通过赋值更改它不会删除它之前指向的对象(尽管 ARC 负责释放它).

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

不,ARC 会为您管理内存.

No, ARC takes care of memory management for you.

一个挑剔:假设 TerrainHexArray 是 NSArray 的一个实例,您不应该将第一个字母大写.这不是语言的要求,但大写类名是惯例,但对变量名使用小写首字母.terrainHexArray 会更合适,并使代码更具可读性.

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.

这篇关于在Objective c中存储指向数组中对象的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆