简体   繁体   English

ObjC - 从数组中的对象获取值(NSMutableArray)

[英]ObjC – Getting values from Objects in array(NSMutableArray)

I'm totally new to ObjC. 我是ObjC的新手。 I've already watched/read some tutorials. 我已经看过/阅读了一些教程。 But now i would like to know how to make an array of objects and print out their values. 但现在我想知道如何制作一个对象数组并打印出它们的值。 I'm coming from a Java perspective. 我是从Java角度出发的。 In Java it would look like this. 在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);

How would the equivalent in ObjC look like? ObjC中的等价物怎么样? I've only come that far: 我只走到这一步:

NSMutableArray * objects = [NSMutableArray  arrayWithCapacity:100];

it could go something like this (take into account that it could be written more compact, but that would mystify the code for a beginner): 它可能是这样的(考虑到它可以写得更紧凑,但这会使初学者的代码神秘化):

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]);
}

Kind regards, PB 亲切的问候,PB

Not sure what your MyClass looks like, but if you wanted to add just integer objects you could do the following. 不确定你的MyClass是什么样的,但是如果你想只添加整数对象,你可以执行以下操作。 Also, MutableArray resizes as needed so it is not quite like your case when you fix your array size to 100. 此外,MutableArray会根据需要调整大小,因此当您将数组大小修复为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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM