Objective-C Language NSArray Accessing elements

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

NSArray *myColors = @[@"Red", @"Green", @"Blue", @"Yellow"];
// Preceding is the preferred equivalent to [NSArray arrayWithObjects:...]

Getting a single item

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, NSArrays 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.

First and Last Item

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


Got any Objective-C Language Question?