TExcelTAD
Home › Objective-C › NSMutableArray

NSMutableArray

NSMutableArray is the growable subclass of NSArray. It keeps every NSArray method and adds methods to add, insert, remove, replace and reorder elements in place.

Adding and inserting

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

int main(void) {
    @autoreleasepool {
        NSMutableArray *queue = [NSMutableArray array];
        [queue addObject:@"Alice"];
        [queue addObject:@"Bob"];
        [queue insertObject:@"VIP Carol" atIndex:0];        // jump the queue
        [queue addObjectsFromArray:@[@"Dan", @"Eve"]];

        NSLog(@"%lu waiting: %@", (unsigned long)queue.count, [queue componentsJoinedByString:@", "]);

        queue[1] = @"Alicia";             // replace with subscript
        queue[queue.count] = @"Frank";    // assigning at index == count appends
        NSLog(@"%@", [queue componentsJoinedByString:@", "]);
    }
    return 0;
}
5 waiting: VIP Carol, Alice, Bob, Dan, Eve
VIP Carol, Alicia, Bob, Dan, Eve, Frank

To create a mutable array from a literal, use [@[…] mutableCopy] or [NSMutableArray arrayWithArray:…].

Removing

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

int main(void) {
    @autoreleasepool {
        NSMutableArray *tasks = [@[@"email", @"call", @"lunch", @"call", @"review"] mutableCopy];

        [tasks removeObject:@"call"];           // removes EVERY equal object
        NSLog(@"after removeObject: %@", [tasks componentsJoinedByString:@" "]);

        [tasks removeObjectAtIndex:0];
        NSLog(@"after removeObjectAtIndex:0: %@", [tasks componentsJoinedByString:@" "]);

        [tasks removeLastObject];
        NSLog(@"after removeLastObject: %@", [tasks componentsJoinedByString:@" "]);

        [tasks removeAllObjects];
        NSLog(@"after removeAllObjects: %lu left", (unsigned long)tasks.count);
    }
    return 0;
}
after removeObject: email lunch review
after removeObjectAtIndex:0: lunch review
after removeLastObject: lunch
after removeAllObjects: 0 left

Note: removeObject: removes all occurrences, compared with isEqual:. To remove just one, find its index and use removeObjectAtIndex:.

Reordering in place

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

int main(void) {
    @autoreleasepool {
        NSMutableArray *ranks = [@[@"bronze", @"gold", @"silver"] mutableCopy];
        [ranks exchangeObjectAtIndex:0 withObjectAtIndex:1];
        NSLog(@"exchanged: %@", [ranks componentsJoinedByString:@" "]);

        NSMutableArray *nums = [@[@42, @7, @19, @3] mutableCopy];
        [nums sortUsingSelector:@selector(compare:)];
        NSLog(@"sorted: %@", [nums componentsJoinedByString:@" "]);

        NSArray *reversed = [[nums reverseObjectEnumerator] allObjects];
        NSLog(@"reversed copy: %@", [reversed componentsJoinedByString:@" "]);
    }
    return 0;
}
exchanged: gold bronze silver
sorted: 3 7 19 42
reversed copy: 42 19 7 3

Don't mutate while enumerating

Changing an array inside a for … in loop over the same array raises an exception ("collection was mutated while being enumerated"). Collect the changes first, or loop over a copy:

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

int main(void) {
    @autoreleasepool {
        NSMutableArray *numbers = [@[@1, @2, @3, @4, @5, @6] mutableCopy];

        // Option 1: loop over a copy
        for (NSNumber *n in [numbers copy]) {
            if (n.integerValue % 2 == 0) {
                [numbers removeObject:n];
            }
        }
        NSLog(@"odd numbers: %@", [numbers componentsJoinedByString:@" "]);

        // Option 2: collect indexes, then remove them in one go
        NSMutableArray *words = [@[@"keep", @"drop", @"keep", @"drop"] mutableCopy];
        NSIndexSet *dropIdx = [words indexesOfObjectsPassingTest:^BOOL(NSString *w, NSUInteger i, BOOL *stop) {
            return [w isEqualToString:@"drop"];
        }];
        [words removeObjectsAtIndexes:dropIdx];
        NSLog(@"words: %@", [words componentsJoinedByString:@" "]);
    }
    return 0;
}
odd numbers: 1 3 5
words: keep keep

Exposing mutable arrays safely

A class usually keeps an NSMutableArray privately and exposes only an immutable NSArray copy, so callers can't change its contents behind its back:

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

@interface Playlist : NSObject
@property (nonatomic, readonly) NSArray *songs;
- (void)addSong:(NSString *)title;
@end

@implementation Playlist {
    NSMutableArray *_songs;
}
- (instancetype)init {
    self = [super init];
    if (self) { _songs = [NSMutableArray array]; }
    return self;
}
- (NSArray *)songs {
    return [_songs copy];          // an immutable snapshot
}
- (void)addSong:(NSString *)title {
    if (![_songs containsObject:title]) {
        [_songs addObject:title];
    }
}
@end

int main(void) {
    @autoreleasepool {
        Playlist *mix = [Playlist new];
        [mix addSong:@"Sunrise"];
        [mix addSong:@"Tides"];
        [mix addSong:@"Sunrise"];      // duplicate ignored
        NSArray *snapshot = mix.songs;
        [mix addSong:@"Afterglow"];
        NSLog(@"snapshot: %@", [snapshot componentsJoinedByString:@", "]);
        NSLog(@"now: %@", [mix.songs componentsJoinedByString:@", "]);
    }
    return 0;
}
snapshot: Sunrise, Tides
now: Sunrise, Tides, Afterglow

Test yourself

How do you make a mutable array from @[@1, @2]?

  1. (NSMutableArray *)@[@1, @2]
  2. [@[@1, @2] mutableCopy]
  3. @m[@1, @2]
  4. [@[@1, @2] copy]

What does [list removeObject:@"x"] remove?

  1. The first "x"
  2. The last "x"
  3. Every element equal to "x"
  4. Nothing unless it's the same pointer

What happens if you add to an array while enumerating it with for-in?

  1. The new item is visited too
  2. The new item is skipped
  3. An exception is raised
  4. Nothing special