NSDictionary
An NSDictionary stores key → value pairs, like a phone book: you look up a value by its key instead of by position. Keys are unique (usually NSStrings), values can be any object. NSDictionary is immutable; NSMutableDictionary can change.
Creating and reading
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSDictionary *capitals = @{
@"France": @"Paris",
@"Japan": @"Tokyo",
@"Kenya": @"Nairobi",
};
NSLog(@"%lu entries", (unsigned long)capitals.count);
NSLog(@"Japan -> %@", capitals[@"Japan"]);
NSLog(@"Kenya -> %@", [capitals objectForKey:@"Kenya"]);
NSString *peru = capitals[@"Peru"]; // missing key: nil, no crash
NSLog(@"Peru -> %@", peru ?: @"unknown");
}
return 0;
}3 entries
Japan -> Tokyo
Kenya -> Nairobi
Peru -> unknown
Looking up a missing key returns nil. This makes if (dict[key]) a quick "does it exist?" test.
Keys, values and order
A dictionary has no defined order. allKeys returns the keys in whatever order the hash table stores them, and that order differs between platforms and runs of different programs. When order matters, sort the keys:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSDictionary *stock = @{@"pears": @12, @"apples": @30, @"kiwis": @0, @"figs": @7};
NSArray *sortedKeys = [stock.allKeys sortedArrayUsingSelector:@selector(compare:)];
for (NSString *fruit in sortedKeys) {
NSLog(@"%-7@ %@", fruit, stock[fruit]);
}
NSInteger total = 0;
for (NSNumber *n in stock.allValues) {
total += n.integerValue;
}
NSLog(@"total items: %ld", (long)total);
NSArray *empty = [stock allKeysForObject:@0];
NSLog(@"out of stock: %@", [empty componentsJoinedByString:@", "]);
}
return 0;
}apples 30
figs 7
kiwis 0
pears 12
total items: 49
out of stock: kiwis
NSMutableDictionary
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSMutableDictionary *settings = [NSMutableDictionary dictionary];
settings[@"theme"] = @"dark"; // add
settings[@"fontSize"] = @14;
[settings setObject:@YES forKey:@"autosave"]; // the long form
settings[@"fontSize"] = @16; // replace: keys are unique
[settings removeObjectForKey:@"autosave"]; // remove
[settings addEntriesFromDictionary:@{@"language": @"en", @"theme": @"light"}];
for (NSString *key in [settings.allKeys sortedArrayUsingSelector:@selector(compare:)]) {
NSLog(@"%@ = %@", key, settings[key]);
}
}
return 0;
}fontSize = 16
language = en
theme = light
addEntriesFromDictionary: overwrites existing keys (theme became light).
Note: Neither keys nor values may be
nil.@{@"name": nilVariable}raises an exception at run time. With a mutable dictionary,dict[key] = nilremoves the key instead.
Counting with a dictionary
A classic use: counting how often each word appears.
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *text = @"to be or not to be that is the question to ask";
NSMutableDictionary *counts = [NSMutableDictionary dictionary];
for (NSString *word in [text componentsSeparatedByString:@" "]) {
NSNumber *current = counts[word];
counts[word] = @(current.integerValue + 1); // nil.integerValue is 0
}
NSArray *words = [counts.allKeys sortedArrayUsingSelector:@selector(compare:)];
for (NSString *word in words) {
NSInteger n = [counts[word] integerValue];
if (n > 1) {
NSLog(@"%@: %ld", word, (long)n);
}
}
NSLog(@"%lu distinct words", (unsigned long)counts.count);
}
return 0;
}be: 2
to: 3
9 distinct words
The trick current.integerValue + 1 works even for a new word: current is nil, and messaging nil returns 0.
Nested data
Dictionaries and arrays nest freely, which is how JSON-like data looks in Objective-C:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSDictionary *user = @{
@"name": @"Priya",
@"roles": @[@"admin", @"editor"],
@"address": @{@"city": @"Pune", @"zip": @"411001"},
};
NSLog(@"%@ lives in %@", user[@"name"], user[@"address"][@"city"]);
NSLog(@"roles: %@", [user[@"roles"] componentsJoinedByString:@", "]);
NSLog(@"via key path: %@", [user valueForKeyPath:@"address.zip"]);
}
return 0;
}Priya lives in Pune
roles: admin, editor
via key path: 411001
valueForKeyPath: walks through nested dictionaries with a dotted path; it is part of Key-Value Coding, covered later.
Key requirements
Any object can be a key if it implements isEqual: and hash consistently and conforms to NSCopying: the dictionary copies its keys, so a mutable string used as a key can't change behind its back. Strings and numbers are by far the most common keys.
| Method | Purpose |
|---|---|
dict[key], objectForKey: |
look up (nil if missing) |
count, allKeys, allValues |
size and contents |
allKeysForObject: |
keys whose value is equal to an object |
dict[key] = value, setObject:forKey: |
add or replace (mutable) |
removeObjectForKey:, removeAllObjects |
remove (mutable) |
addEntriesFromDictionary: |
merge (mutable) |
Test yourself
What does dict[@"missing"] return for a key that isn't present?
- NSNull
- nil
- an empty string
- it raises an exception
In what order does allKeys return the keys?
- Insertion order
- Alphabetical order
- No guaranteed order
- Reverse insertion order
What happens with settings[@"theme"] = @"light" when theme already exists?
- A second entry is added
- The value is replaced
- An exception is raised
- Nothing