views:

102

answers:

5

I'm quite new to objective-c. I have problems when creating array of objects. In java it is possible to make array of object and can access individual instances directly.

For example,

SomeClass[] instance = new SomeClass[10];
instance[i].var=10;

Is there any way to do like this in objetive-c? Can I access the instance variable in array of object directly using index? An example would be of more help. Thanks in advance

A: 

Seems so: http://www.cocoalab.com/?q=node/19

Amigable Clark Kant
+4  A: 

You can use both NSArray (documented by other answers) and standard C arrays. In the latter case, you would do:

id numbers[10];
NSInteger i;
for (i = 0; i < 10; i++) {
  numbers[i] = [NSNumber numberWithInteger: i];
}

note that unlike in Java, there is no type id[], or NSString[], or anything. A primitive array is just the same as in C: a pointer and a cursor.

Graham Lee
+6  A: 

Using the Foundation Framework (which you almost certainly will be if you're using Objective-C):

NSString *object1 = @"an object";
NSString *object2 = @"another object";
NSArray *myArray = [NSArray arrayWithObjects:object1, object2, nil];

NSString *str = [myArray objectAtIndex:1];

Here, str will be a reference to object 2 (which contains another object). Note that the nil 'terminates' the list of objects in the array, and is required. If you want a mutable (modifiable) array:

NSString *object1 = @"an object";
NSString *object2 = @"another object";
NSMutableArray *myMutableArray = [NSMutableArray array];

[myMutableArray addObject:object1];
[myMutableArray addObject:object2];
Nick Forge
after adding the object to array, can i able to modify the data? will it reflect in array?
Ka-rocks
You're just adding an object reference into the array. Any changes you make to the object in the array will be reflected wherever else you're using that object
peelman
A: 

References to objective-C classes are just pointers, so you can just create a c array of pointers:

NSNumber* numbers[10];
for (int i=0; i<10; i++)
{
    numbers[i] = [NSNumber numberWithInt:i];
}
NSLog(@"%@ %@ %@ %@ %@ %@ %@ %@ %@ %@", numbers[0], numbers[1], numbers[2], numbers[3], numbers[4], numbers[5], numbers[6], numbers[7], numbers[8], numbers[9]);
//0 1 2 3 4 5 6 7 8 9

However, you're better off using NSArray.

Benedict Cohen
A: 
SomeClass[] instance = new SomeClass[10];
instance[i].var=10;

The closest you can get to the above in Objective-C is something like:

NSMutableArray* instances = [[NSMutableArray alloc] init];
[instances addObject: foo];
[instances addObject: bar];
// etc. mutable arrays grow as you add elements to them

[[instances objectAtIndex: i] setVar: 10];

What type are the objects you add to the array? Well, it doesn't matter as long as they respond to the messages you choose to send them. so as long as the object at index i in the instances array responds to the selector -setVar: and -expects an integer as its parameter, the above code will be fine.

JeremyP