< Previous PageNext Page > Hide TOC

Dictionaries: Collections of Keys and Values

Dictionaries manage pairs of keys and values. Use a dictionary when you need a convenient and efficient way to retrieve data associated with an arbitrary key. An NSDictionary object manages a static array; that is, an array whose keys and values cannot be removed, replaced, or added to. However, the individual elements can be modified. An NSMutableDictionary, a subclass of NSDictionary, allows you to add and delete entries at any time, automatically allocating memory as needed. You can easily convert one type of dictionary to the other with the initializer that takes a dictionary as an argument.

Contents:

Dictionary Fundamentals
Primitive Methods
Using Mutable Dictionaries
Sorting a Dictionary


Dictionary Fundamentals

A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key, and a second object which is that key’s value. Within a dictionary, the keys are unique—that is, no two keys in a single dictionary are equal (as determined by equals or isEqual:). A key does not have to be a string, it can be any object that adopts the NSCopying protocol.

Methods that add entries to dictionaries—whether as part of initialization (for all dictionaries) or during modification (for mutable dictionaries)— don’t add each value object to the dictionary directly, but copy each key argument and add the copy to the dictionary. Each corresponding value object receives a retain message to ensure that it won’t be deallocated before the dictionary is finished with it.

Important: Because the dictionary copies each key, keys must conform to the NSCopying protocol). You should also bear this in mind when choosing what objects to use as keys. Although you can use any object that adopts the NSCopying protocol, it is typically bad design to use large objects such as instances of NSImage since this may incur performance penalties.

Internally, a dictionary uses a hash table to organize its storage and to provide rapid access to a value given the corresponding key. However, the methods defined for dictionaries insulate you from the complexities of working with hash tables, hashing functions, or the hashed value of keys. The methods take keys directly, not their hashed form.

You create a temporary dictionary by sending one of the dictionary... messages to the class object.

Primitive Methods

NSDictionary’s three primitive methods—count, objectForKey:, and keyEnumerator—provide the basis for all of the other methods in its interface. The count method returns the number of entries in the dictionary. objectForKey: returns the value associated with a given key. keyEnumerator returns an object that lets you iterate through each of the keys in the dictionary. NSDictionary’s other methods operate by invoking one or more of these primitives. The non-primitive methods provide convenient ways of accessing multiple entries at once. And the Objective-C methods description... and writeToFile:atomically: cause a dictionary to write a representation of itself to a string or to a file, respectively.

NSMutableDictionary’s primitive methods—setObjectForKey: and removeObjectForKey:—add modification operations to the basic operations it inherits from NSDictionary. Its other methods invoke one or both of these primitives. They provide convenient ways of adding or removing multiple entries at a time.

Using Mutable Dictionaries

You must be careful when removing an entry from a mutable dictionary, since the key and value objects that make up the entry receive release messages. If there are no further references to the objects, they’re deallocated. Note that if your program keeps a reference to such an object, the reference will become invalid unless you remember to send the object a retain message before it’s removed from the dictionary. For example, the third statement below will result in a run-time error if the dictionary is the only owner of the anObject:

id anObject = [aDictionary objectForKey:theKey];
 
[aDictionary removeObjectForKey:theKey];
[anObject someMessage]; // likely crash

To guard against this possibility, you can retain a value object before you remove it, as illustrated in this example:

id anObject = [[aDictionary objectForKey:theKey] retain];
 
[aDictionary removeObjectForKey:theKey];
[anObject someMessage];

Sorting a Dictionary

NSDictionary provides the method keysSortedByValueUsingSelector: which returns an array of the dictionary’s keys in the order they would be in if the dictionary were sorted by its values, as illustrated in the following example:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithInt:63], @"Mathematics",
    [NSNumber numberWithInt:72], @"English",
    [NSNumber numberWithInt:55], @"History",
    [NSNumber numberWithInt:49], @"Geography",
    nil];
 
NSArray *sortedKeysArray =
    [dict keysSortedByValueUsingSelector:@selector(compare:)];
// sortedKeysArray contains: (Geography, History, Mathematics, English)


< Previous PageNext Page > Hide TOC


© 2009 Apple Inc. All Rights Reserved. (Last updated: 2009-02-04)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.