Table of Contents Previous Section

Commonly Used Dictionary Methods

The following sections list some of the most commonly used methods of NSDictionary and NSMutableDictionary. The methods covered are grouped in the following categories:

Creating Dictionaries

The methods in this section are class methods, as denoted by the plus sign (+). You use class methods to send messages to a class-in this case, NSDictionary and NSMutableDictionary. For more information on class methods, see "Messaging in WebScript" in the "Using WebScript" chapter.

+ dictionary
Returns an empty dictionary. Usually used to create NSMutableDictionaries. NSDictionaries created with this method are permanently empty.
// Most common use
id mutableDictionary = [NSMutableDictionary dictionary];

// May not be what you want
id dictionary = [NSDictionary dictionary];

+ dictionaryWithObjects:forKeys:
Returns a dictionary containing entries constructed from the contents of a specified array of objects and a specified array of keys. The two arrays must have the same number of elements.
id preferences = [NSMutableDictionary
		dictionaryWithObjects:@("window", "non-smoking", "747")
		forKeys:@("seatAssignment", "smoking", "aircraft")];

+ dictionaryWithObjectsAndKeys:
Returns a dictionary containing entries constructed from a specified set of objects and keys. dictionaryWithObjectsAndKeys: takes a variable number of arguments: a list of alternating objects and keys ending with nil.
id customerPreferences = [NSDictionary dictionaryWithObjectsAndKeys:
		seatingPreference, @"seatAssignment", 
		smokingPreference, @"smoking",
		aircraftPreference, @"aircraft", nil];

+ dictionaryWithDictionary:
Returns a dictionary containing the contents of a specified dictionary. Usually used to create an NSMutableDictionary from an immutable NSDictionary.

+ dictionaryWithContentsOfFile:
Returns a dictionary initialized from the contents of a specified file. The specified file can be a full or relative pathname; the file that it names must contain a string representation of a dictionary, such as that produced by the writeToFile:atomically: method.
See also description.

Querying Dictionaries

- allKeys
Returns an array containing the dictionary's keys or an empty array if the dictionary has no entries. This method is useful for accessing all the entries in a dictionary. For example, the following code excerpt:
id index;
id keys = [dictionary allKeys];
for (index = 0; index < [keys count]; index++) {
	value = [dictionary objectForKey:[keys objectAtIndex:index];
	// Use the value
}

creates the NSArray keys and uses it to access the value of each entry in the dictionary.

- allKeysForObject:
Returns an array containing all the keys corresponding to values equivalent to a specified object. Equivalency is determined using the isEqual: method. If the specified object isn't equivalent to any of the values in the receiver, this method returns nil.

- allValues:
Returns an array containing the dictionary's values, or an empty array if the dictionary has no entries.
Note that the array returned from allValues may have a different count than the array returned from allKeys. An object can be in a dictionary more than once if it corresponds to multiple keys.

- keysSortedByValueUsingSelector:
Returns an NSArray containing the dictionary's keys such that their corresponding values are sorted in ascending order, as determined by a specified method. For example, the following code excerpt:
id choices = @{"Steak" = 3; "Seafood" = 2; "Pasta" = 1};
id keys = [choices sortedByValueUsingSelector:@"compare:"];

creates the NSArray keys containing the string "Pasta" at index 0, "Seafood" at index 1, and "Steak" at index 2.

- count
Returns the number of entries currently in the dictionary.

- isEqual:
Returns YES if the specified object is a dictionary and has contents equivalent to the receiver, NO otherwise. Two dictionaries have equivalent contents if they each hold the same number of entries and, for a given key, the corresponding value objects in each dictionary satisfy the isEqual: test.

- objectForKey:
Returns the object that corresponds to a specified key. For example, the following code excerpt:
id preferences = [NSMutableDictionary
		dictionaryWithObjects:@("window", "non-smoking", "747")
		forKeys:@("seatAssignment", "section", "aircraft")];
id sectionPreference = [dictionary objectForKey:@"section"];

produces the NSString sectionPreference with the contents "non-smoking".

Adding, Removing, and Modifying Entries

Warning: The following methods are not supported by NSDictionary. They are only available to NSMutableDictionary objects.

- setObject:forKey:
Adds an entry to the receiver, consisting of a specified key and its corresponding value object. If the receiver already has an entry for the specified key, the previous value for that key is replaced with the argument for setObject:. For example, the following code excerpt:
id dictionary = [NSMutableDictionary dictionaryWithDictionary:
		@{"seatAssignment" = "window"}];
[dictionary setObject:@"non-smoking" forKey:@"section"];
[dictionary setObject:@"aisle" forKey:@"seatAssignment"];

produces the NSMutableDictionary dictionary with the value "non-smoking" for the key "section" and the value "aisle" for the key "seatAssignment." Notice that the original value for "seatAssignment" is replaced.

It is an error to specify nil as an argument for setObject: or forKey:. You can't put nil in a dictionary as a key or as a value.

- addEntriesFromDictionary:
Adds the entries from a specified dictionary to the receiver. If both dictionaries contain the same key, the receiver's previous value for that key is replaced with the new value.

- removeAllObjects
Empties the dictionary of its entries.

- removeObjectForKey:
Removes the entry for a specified key.

- removeObjectsForKeys:
Removes the entries for each key in a specified array.

- setDictionary:
Removes all the entries in the receiver, then adds the entries from a specified dictionary.

Representing Dictionaries as Strings

- description
Returns a string that represents the contents of the receiver. For example, the following code excerpt:
id preferences = [NSMutableDictionary
		dictionaryWithObjects:@("window", "non-smoking", "747")
		forKeys:@("seatAssignment", "section", "aircraft")];
id description = [preferences description];

produces the string "{"seatAssignment" = "Window"; "section" = "Non-smoking"; "aircraft" = "747"}".

Storing Dictionaries

- writeToFile:atomically:
Writes the dictionary's string representation to a specified file using the description method. Returns YES on success and NO on failure. If YES is specified for atomically:, this method attempts to write the file safely so that an existing file with the specified path is not overwritten, and it does not create a new file at the specified path unless the write is successful. The resulting file is suitable for use with dictionaryWithContentsOfFile:. For example, the following excerpt:
id defaults = [NSMutableDictionary
		dictionaryWithContentsOfFile:path];
[defaults setObject:newLanguagePreference forKey:@"Language"];
[defaults writeToFile:path atomically:YES];

creates an NSMutableDictionary from the contents of the file specified by path, updates the object for the key @"Language", and saves the updated dictionary back to the same file.

See also description.

Table of Contents Next Section