0

我对 ObjC 完全陌生。我已经看过/阅读了一些教程。但现在我想知道如何制作一个对象数组并打印出它们的值。我是从 Java 的角度来的。在 Java 中,它看起来像这样。

MyClass [] objects = new MyClass[100];

for(int i = 0; i < objects.length;i++)
   int value = i;
   objects[i] = new MyClass(value);

for(int i = 0; i < objects.length;i++)
   println(objects[i].value);

ObjC 中的等价物会是什么样子?我只走了这么远:

NSMutableArray * objects = [NSMutableArray  arrayWithCapacity:100];
4

2 回答 2

1

Not sure what your MyClass looks like, but if you wanted to add just integer objects you could do the following. Also, MutableArray resizes as needed so it is not quite like your case when you fix your array size to 100.

NSMutableArray *objects = [NSMutableArray arrayWithCapacity:100];

for(int i = 0; i < 100; ++i)
    [objects addObject:[NSNumber numberWithInt:i]];

for(id object in objects) {
    NSLog(@"%@\n",object);
}
于 2013-09-01T15:47:01.360 回答
1

它可以是这样的(考虑到它可以写得更紧凑,但这会使初学者的代码变得神秘):

const int NR_ELEMENTS = 100;

NSMutableArray *objects = [NSMutableArray arrayWithCapacity:NR_ELEMENTS];

for (int i=0; i < NR_ELEMENTS; i++)
{
    MyClass *mc = [[MyClass alloc] initWith:i];
    [objects addObject:mc];
}

for (int i=0; i < NR_ELEMENTS; i++)
{
    // Suppose MyClass.value is integer
    NSLog(@"%i\n", [[objects objectAtIndex:i] value]);
}

亲切的问候,PB

于 2013-09-01T15:44:28.380 回答