Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท Foundation Framework

NSArray, NSDictionary and NSSet

Master Foundation collections in Objective-C - literals, mutable and immutable variants, fast enumeration, sorting, filtering with predicates, generics, nil handling and a hash table stand-in.

Foundation gives Objective-C three core collections: NSArray (an ordered list), NSDictionary (key-value pairs) and NSSet (an unordered group of unique items). Each comes in an immutable and a mutable form (NSMutableArray, and so on). They hold objects only: you cannot put an int or a C struct directly into one, which is why NSNumber and NSValue exist.

NSArray

OBJECTIVEC
NSArray *fruits = @[@"apple", @"banana", @"cherry"];       // literal, immutable
NSString *first = fruits[0];                               // subscript, same as objectAtIndex:
NSUInteger count = fruits.count;                           // 3
BOOL has = [fruits containsObject:@"banana"];              // YES
NSUInteger idx = [fruits indexOfObject:@"cherry"];         // 2 (NSNotFound if absent)
NSString *last = fruits.lastObject;                        // "cherry", nil if the array is empty

Accessing an index out of range throws NSRangeException and crashes. Check count first, or use firstObject/lastObject, which return nil for an empty array.

NSMutableArray

OBJECTIVEC
NSMutableArray *todo = [NSMutableArray arrayWithObjects:@"write", @"test", nil];
[todo addObject:@"ship"];
[todo insertObject:@"plan" atIndex:0];
[todo removeObject:@"test"];
[todo removeObjectAtIndex:0];
[todo replaceObjectAtIndex:0 withObject:@"WRITE"];
[todo exchangeObjectAtIndex:0 withObjectAtIndex:1];

Collections cannot contain nil. Adding nil throws. When you need "no value", use [NSNull null].

NSDictionary

OBJECTIVEC
NSDictionary *user = @{
    @"name":  @"Ada",
    @"age":   @36,
    @"admin": @YES
};
NSString *name = user[@"name"];          // "Ada"
id missing = user[@"email"];             // nil, not an error
NSArray *keys = user.allKeys;            // order is not guaranteed
NSArray *vals = user.allValues;

NSMutableDictionary *settings = [NSMutableDictionary dictionary];
settings[@"theme"] = @"dark";
settings[@"volume"] = @7;
[settings removeObjectForKey:@"volume"];
settings[@"theme"] = nil;                // assigning nil via subscript removes the key

Keys must conform to NSCopying and implement hash and isEqual:. NSString and NSNumber are the usual choices.

NSSet

OBJECTIVEC
NSSet *tags = [NSSet setWithArray:@[@"ios", @"mac", @"ios", @"watch"]];   // 3 unique items
BOOL has = [tags containsObject:@"mac"];                                  // fast lookup
NSMutableSet *seen = [NSMutableSet set];
[seen addObject:@"x"];

NSSet *a = [NSSet setWithObjects:@1, @2, @3, nil];
NSSet *b = [NSSet setWithObjects:@2, @3, @4, nil];
NSMutableSet *both = [a mutableCopy];
[both intersectSet:b];                                                    // {2, 3}

NSOrderedSet keeps uniqueness and insertion order, and NSCountedSet counts duplicates.

Fast enumeration and blocks

OBJECTIVEC
for (NSString *fruit in fruits) {
    NSLog(@"%@", fruit);
}
for (NSString *key in user) {                // iterating a dictionary gives its keys
    NSLog(@"%@ = %@", key, user[key]);
}
[user enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    NSLog(@"%@ -> %@", key, obj);
}];

Do not mutate a collection while you enumerate it: it raises an exception. Iterate over a copy, or collect items to remove and delete them afterwards.

Sorting, filtering and mapping

OBJECTIVEC
NSArray *numbers = @[@5, @3, @8, @1];
NSArray *asc = [numbers sortedArrayUsingSelector:@selector(compare:)];     // 1 3 5 8

NSSortDescriptor *byAge = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
NSArray *people = [peopleArray sortedArrayUsingDescriptors:@[byAge]];

NSPredicate *adults = [NSPredicate predicateWithFormat:@"age >= %d", 18];
NSArray *filtered = [peopleArray filteredArrayUsingPredicate:adults];

NSArray *names = [people valueForKey:@"name"];            // map by key path (see KVC)
NSNumber *total = [numbers valueForKeyPath:@"@sum.self"]; // 17

There is no built-in map/reduce/filter method, but enumerateObjectsUsingBlock:, indexesOfObjectsPassingTest: and key paths cover those needs.

Generics

Lightweight generics document and check element types at compile time:

OBJECTIVEC
NSArray<NSString *> *names = @[@"Ada", @"Grace"];
NSDictionary<NSString *, NSNumber *> *scores = @{ @"Ada": @98 };
NSMutableArray<NSNumber *> *ids = [NSMutableArray array];

They are erased at runtime, so they prevent warnings, not crashes.

Immutable and mutable: copy rules

[array copy] returns an immutable array (the same object if it is already immutable), and [array mutableCopy] returns a new mutable one. Copies are shallow: the element objects are shared, not duplicated. If you store a collection in a property, declare it copy. See property attributes.

What a dictionary is: a hash table

NSDictionary hashes each key to find a bucket. The C stand-in below builds a small hash table with chaining, and a set built on top of it, to show why lookups are fast and why keys need a stable hash and isEqual:.

C Stand-in: a hash table behind NSDictionary and NSSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Sorting by hand

The comparator you give to sortedArrayUsingComparator: is the same idea as C's qsort callback. This stand-in sorts records by two keys, like a chain of sort descriptors:

C Stand-in: sort descriptors with qsort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if you add nil to an NSMutableArray?

    Collections cannot hold nil; use [NSNull null] as a placeholder.
  2. 2. What does user[@"email"] return if the key is absent?

    Missing keys give nil, which is why you check before using the value.
  3. 3. Which collection guarantees uniqueness and is optimized for membership tests?

    NSSet stores each distinct object once and uses hashing for fast lookup.
  4. 4. What is wrong with removing items from an array inside a for...in loop over the same array?

    Fast enumeration forbids changing the collection; iterate a copy instead.

Summary

  • NSArray, NSDictionary and NSSet hold objects only, never nil, and each has a mutable subclass.
  • Literals (@[], @{}) and subscripts keep code short; fast enumeration iterates safely if you do not mutate.
  • Sort with descriptors or comparators, filter with predicates.
  • Copies are shallow, and collection properties should be copy.

Next: NSNumber, NSData and Dates