Maps in Objective-C
Maps are built-in associative data types (sometimes called hashes or dicts in other languages).
To create an empty map, use NSMutableDictionary
.
#import <Foundation/Foundation.h>
int main() {
@autoreleasepool {
NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
Set key/value pairs using the method setObject:forKey:
.
[m setObject:@7 forKey:@"k1"];
[m setObject:@13 forKey:@"k2"];
Printing a map using NSLog
will show all of its key/value pairs.
NSLog(@"map: %@", m);
Get a value for a key using objectForKey:
.
NSNumber *v1 = [m objectForKey:@"k1"];
NSLog(@"v1: %@", v1);
If the key doesn’t exist, nil
is returned.
NSNumber *v3 = [m objectForKey:@"k3"];
NSLog(@"v3: %@", v3);
The method count
returns the number of key/value pairs when called on a map.
NSLog(@"len: %lu", (unsigned long)[m count]);
The method removeObjectForKey:
removes key/value pairs from a map.
[m removeObjectForKey:@"k2"];
NSLog(@"map: %@", m);
To remove all key/value pairs from a map, use removeAllObjects
.
[m removeAllObjects];
NSLog(@"map: %@", m);
The optional second return value when getting a value from a map indicates if the key was present in the map. This can be checked using objectForKey:
and verifying that the return value is not nil
.
NSNumber *prsValue = [m objectForKey:@"k2"];
BOOL prs = prsValue != nil;
NSLog(@"prs: %d", prs);
You can also declare and initialize a new map in the same line with this syntax.
NSMutableDictionary *n = @{ @"foo": @1, @"bar": @2 }.mutableCopy;
NSLog(@"map: %@", n);
A simplified way to compare the dictionaries, assuming you are checking equality by content, could be using isEqualToDictionary:
.
NSMutableDictionary *n2 = @{ @"foo": @1, @"bar": @2 }.mutableCopy;
if ([n isEqualToDictionary:n2]) {
NSLog(@"n == n2");
}
}
return 0;
}
When printed, maps appear in the form {"k1":7, "k2":13}
.
$ clang -fobjc-arc -framework Foundation maps.m -o maps
$ ./maps
map: {
k1 = 7;
k2 = 13;
}
v1: 7
v3: (null)
len: 2
map: {
k1 = 7;
}
map: {
}
prs: 0
map: {
bar = 2;
foo = 1;
}
n == n2