Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is array of Object possible in Objective-C?

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 Objective-C? Can I access the instance variable in array of object directly using index? An example would be of more help. Thanks in advance

like image 910
Ka-rocks Avatar asked Dec 08 '22 01:12

Ka-rocks


1 Answers

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];
like image 184
Nick Forge Avatar answered Dec 24 '22 02:12

Nick Forge