Next: Describing an Array Up: NSArray Previous: arrayWithObjects

Accessing Objects in a NSArray

To access an object in an NSArray, you use the -objectAtIndex: method, as in the following example:
NSArray *numbers;
NSString *string;

numbers = [NSArray arrayWithObjects: @"One", @"Two", @"Three", 
                                     nil];
string = [numbers objectAtIndex: 2];   // @"Three"
Of course, you have to be careful not to ask for an object at an index which is negative or bigger than the size of the array; if you do, an NSRangeException is raised (we'll learn more about exceptions in another tutorial).

To get the length of an array, you use the method -count, as in:

NSArray *numbers;
int i;

numbers = [NSArray arrayWithObjects: @"One", @"Two", @"Three", 
                                     nil];
i = [numbers count];   // 3



Nicola 2002-01-13