0

I'm totally new to 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. In Java it would look like this.

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? I've only come that far:

NSMutableArray * objects = [NSMutableArray  arrayWithCapacity:100];
1
  • 1
    arrayWithCapacity: doesn't do what you think; it does not create an array with 100 empty slots. NSArray/NSMutableArray are not sparse arrays. Commented Sep 1, 2013 at 16:37

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

So in the implementation i would do sth like: -(id) initWith:(int)n { value = n; }?
If value would be a property, then you would do [objects objectAtIndex:i].value I intended value to be a function returning a private property, hence [[objects objectAtIndex:i] value]. So you would do: -(id) initWith:(int)n { privateProperty = n; } and - (int) value { return privateProperty; }
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);
}

1 Comment

I'm having two functions in the object:-(void)setAge: (int) a; -(void)setWeight: (int) w; Now i would like to set these two integers (age, weight) when i create the instances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.