1.24. Allocating and Making Use of Dictionaries
Problem
You want to store key-value data in an object, or you would like to retrieve objects from an array using a key into the array, but arrays won’t quite suffice for this purpose, as they do not facilitate finding objects inside the array using a key or a marker for that object.
Solution
Use NSDictionary and its
mutable counterpart, NSMutableDictionary.
Discussion
A dictionary is a special container for objects in which each object is given a key, which itself is an object. That is one of the key differences between dictionaries and arrays. An array has a numeric index into each item/object that it holds whereas a dictionary holds a key to each item. I’ll show you what I mean.
Let’s say we want to store a person’s first name, last name, and age into an array and then into a dictionary. This is how we would store those values in an array:
NSArray *person = [[NSArray alloc] initWithObjects:
@"Anthony",
@"Robbins",
[NSNumber numberWithUnsignedInteger:51], nil];
NSLog(@"First Name = %@", [person objectAtIndex:0]);
NSLog(@"Last Name = %@", [person objectAtIndex:1]);
NSLog(@"Age = %@", [person objectAtIndex:2]);You can see that we are using an index into the array to access
each one of these values. With dictionaries, we give each value a
key, which is an object, and then use that key to
access those values. Let’s see the same example, using dictionaries.
We have a "First Name" key with the
value "Anthony" and so on:
NSNumber *age = [NSNumber ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access