Next: 2.6 Describing an Array Up: 2 NSArray Previous: 2.4 arrayWithObjects

2.5 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



2008-01-16