NSArray *myColors = @[@"Red", @"Green", @"Blue", @"Yellow"];
// Preceding is the preferred equivalent to [NSArray arrayWithObjects:...]
The objectAtIndex:
method provides a single object. The first object in an NSArray
is index 0. Since an NSArray
can be homogenous (holding different types of objects), the return type is id
("any object"). (An id
can be assigned to a variable of any other object type.) Importantly, NSArray
s can only contain objects. They cannot contain values like int
.
NSUInteger idx = 2;
NSString *color = [myColors objectAtIndex:idx];
// color now points to the string @"Green"
Clang provides a better subscript syntax as part of its array literals functionality:
NSString *color = myColors[idx];
Both of these throw an exception if the passed index is less than 0 or greater than count - 1
.
NSString *firstColor = myColors.firstObject;
NSString *lastColor = myColors.lastObject;
The firstObject
and lastObject
are computed properties and return nil
rather than crashing for empty arrays. For single element arrays they return the same object. Although, the firstObject
method was not introduced to NSArray
until iOS 4.0.
NSArray *empty = @[]
id notAnObject = empty.firstObject; // Returns `nil`
id kaboom = empty[0]; // Crashes; index out of bounds