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
.
Set key/value pairs using the method setObject:forKey:
.
Printing a map using NSLog
will show all of its key/value pairs.
Get a value for a key using objectForKey:
.
If the key doesn’t exist, nil
is returned.
The method count
returns the number of key/value pairs when called on a map.
The method removeObjectForKey:
removes key/value pairs from a map.
To remove all key/value pairs from a map, use removeAllObjects
.
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
.
You can also declare and initialize a new map in the same line with this syntax.
A simplified way to compare the dictionaries, assuming you are checking equality by content, could be using isEqualToDictionary:
.
When printed, maps appear in the form {"k1":7, "k2":13}
.