TExcelTAD
Home › Objective-C › NSArray

NSArray

NSArray is an ordered, immutable list of objects. Items are accessed by a zero-based index, and the array can't grow, shrink or change once created (for that, use NSMutableArray, next lesson).

Creating arrays

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *planets = @[@"Mercury", @"Venus", @"Earth", @"Mars"];   // literal
        NSArray *mixed = @[@"text", @42, @YES];                           // any objects
        NSArray *empty = @[];
        NSArray *old = [NSArray arrayWithObjects:@"a", @"b", nil];        // older style, nil-terminated

        NSLog(@"%lu planets", (unsigned long)planets.count);
        NSLog(@"first %@, last %@", planets.firstObject, planets.lastObject);
        NSLog(@"index 2: %@", planets[2]);
        NSLog(@"mixed has %lu items, empty has %lu", (unsigned long)mixed.count, (unsigned long)empty.count);
        NSLog(@"old style: %@", [old componentsJoinedByString:@","]);
    }
    return 0;
}
4 planets
first Mercury, last Mars
index 2: Earth
mixed has 3 items, empty has 0
old style: a,b

Arrays can contain objects of different classes, but not nil and not C values. Box numbers with @, and use [NSNull null] as a placeholder if you really need an "empty" slot.

Accessing elements safely

Reading past the end raises an NSRangeException and, if uncaught, crashes the program. Check count first:

objc · try it yourself
#import <Foundation/Foundation.h>

NSString *itemAt(NSArray *array, NSUInteger index) {
    if (index < array.count) {
        return array[index];
    }
    return @"(out of range)";
}

int main(void) {
    @autoreleasepool {
        NSArray *colors = @[@"red", @"green", @"blue"];
        NSLog(@"%@", itemAt(colors, 1));
        NSLog(@"%@", itemAt(colors, 7));

        // firstObject and lastObject return nil for an empty array instead of crashing
        NSArray *none = @[];
        NSLog(@"first of empty: %@", none.firstObject);
    }
    return 0;
}
green
(out of range)
first of empty: (null)

array[i] is shorthand for [array objectAtIndex:i].

Searching

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *langs = @[@"C", @"Swift", @"Objective-C", @"Swift"];

        NSLog(@"contains Swift? %d", [langs containsObject:@"Swift"]);
        NSLog(@"index of Swift: %lu", (unsigned long)[langs indexOfObject:@"Swift"]);

        NSUInteger idx = [langs indexOfObject:@"Rust"];
        if (idx == NSNotFound) {
            NSLog(@"Rust not found");
        }

        // Find with a condition, using a block
        NSUInteger longIdx = [langs indexOfObjectPassingTest:^BOOL(NSString *s, NSUInteger i, BOOL *stop) {
            return s.length > 5;
        }];
        NSLog(@"first long name: %@ at %lu", langs[longIdx], (unsigned long)longIdx);
    }
    return 0;
}
contains Swift? 1
index of Swift: 1
Rust not found
first long name: Objective-C at 2

containsObject: and indexOfObject: use isEqual:, so they compare contents, not pointers. The ^BOOL(…){…} syntax is a block (an inline function); blocks get their own lessons later.

Deriving new arrays

Since NSArray is immutable, operations return new arrays:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *week = @[@"Mon", @"Tue", @"Wed", @"Thu", @"Fri"];

        NSArray *midweek = [week subarrayWithRange:NSMakeRange(1, 3)];
        NSArray *withWeekend = [week arrayByAddingObjectsFromArray:@[@"Sat", @"Sun"]];
        NSArray *withHoliday = [week arrayByAddingObject:@"Holiday"];

        NSLog(@"midweek: %@", [midweek componentsJoinedByString:@" "]);
        NSLog(@"%lu days with weekend", (unsigned long)withWeekend.count);
        NSLog(@"last: %@", withHoliday.lastObject);
        NSLog(@"original still has %lu", (unsigned long)week.count);

        // Filter with a predicate
        NSPredicate *startsWithT = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH 'T'"];
        NSArray *tDays = [week filteredArrayUsingPredicate:startsWithT];
        NSLog(@"T days: %@", [tDays componentsJoinedByString:@", "]);
    }
    return 0;
}
midweek: Tue Wed Thu
7 days with weekend
last: Holiday
original still has 5
T days: Tue, Thu

Printing arrays

NSLog(@"%@", array) prints the array's description. Its exact layout differs between platforms (on a Mac it's a multi-line list in parentheses), so for clean output join or loop over the elements yourself:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *scores = @[@88, @92, @79];
        NSLog(@"joined: %@", [scores componentsJoinedByString:@" | "]);
        for (NSUInteger i = 0; i < scores.count; i++) {
            NSLog(@"score[%lu] = %@", (unsigned long)i, scores[i]);
        }
    }
    return 0;
}
joined: 88 | 92 | 79
score[0] = 88
score[1] = 92
score[2] = 79

Common methods

Method Purpose
count number of elements
array[i], objectAtIndex: element at an index (crashes if out of range)
firstObject, lastObject first/last element or nil
containsObject:, indexOfObject: search using isEqual:
subarrayWithRange: a slice
arrayByAddingObject: a new array with one more element
componentsJoinedByString: join strings
filteredArrayUsingPredicate: elements matching a condition
sortedArrayUsingSelector: a sorted copy (see Sorting)

Test yourself

What happens when you access array[5] on a 3-element NSArray?

  1. Returns nil
  2. Returns NSNull
  3. Raises an NSRangeException
  4. Returns the last element

Can an NSArray contain nil?

  1. Yes
  2. No; use [NSNull null] as a placeholder
  3. Only at the end
  4. Only in mutable arrays

What does indexOfObject: return when the object isn't found?

  1. -1
  2. 0
  3. NSNotFound
  4. nil