PATH  Documentation > Mac OS X > Foundation Reference: Objective-C



Table of Contents

NSDictionary


Inherits from:
NSObject
Conforms to:
NSCoding
NSCopying
NSMutableCopying
NSObject (NSObject)
Declared in:
Foundation/NSDictionary.h
Foundation/NSFileManager.h



Class at a Glance


An NSDictionary object stores an immutable set of entries.

Principal Attributes


Creation



+ dictionary Returns an empty dictionary.
+ dictionaryWithContentsOfFile: Returns a dictionary initialized from the property list stored in the specified file.
+ dictionaryWithDictionary: Returns a dictionary initialized from an existing dictionary.
+ dictionaryWithObject:forKey: Returns a dictionary initialized with a single object and key.
+ dictionaryWithObjects:forKeys: Returns a dictionary of the specified objects and their keys.
+ dictionaryWithObjects:forKeys:count: Returns a dictionary of the specified objects and their keys.
+ dictionaryWithObjectsAndKeys: Returns a dictionary of the specified objects and their keys.

Commonly Used Methods



- count Returns the number of objects currently in the dictionary.
- objectForKey: Returns the object that corresponds to the specified key.
- keyEnumerator Returns an enumerator object that lets you access each key in the dictionary.


Class Description


The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. Use this class, or its subclass NSMutableDictionary when you need a convenient and efficient way to retrieve data associated with an arbitrary key. (For convenience, we use the term dictionary to refer to any instance of one of these classes without specifying its exact class membership.)

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 isEqual:).

An instance of NSDictionary is an immutable dictionary: You establish its entries when it's created, and cannot modify them afterwards. An instance of NSMutableDictionary is a mutable dictionary: You can add or delete entries at any time, and the object automatically allocates memory as needed.

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 in this cluster insulate you from the complexities of working with hash tables, hashing functions, or the hashed value of keys. The methods described below take keys directly, not their hashed form.

Generally, you create a temporary dictionary by sending one of the dictionary... messages to the class object. These methods return a dictionary containing the associations specified as arguments to the method. Methods that add entries to dictionaries-whether as part of initialization (for all dictionaries) or during modification (for mutable dictionaries)-copy each key argument (keys must conform to the NSCopying protocol) and add the copies to the dictionary. Each corresponding value object receives a retain message to ensure that it won't be deallocated before the dictionary is through with it.

NSDictionary and NSMutableDictionary are part of a class cluster, so the objects you create with this interface are not actual instances of the these two classes. Rather, the instances belong to one of their private subclasses. Although a dictionary's class is private, its interface is public, as declared by these abstract superclasses, NSDictionary and NSMutableDictionary.

The dictionary classes adopt the NSCopying and NSMutableCopying protocols, making it convenient to convert a dictionary of one type to the other.

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.

The other methods declared here operate by invoking one or more of these primitives. The non-primitive methods provide convenient ways of accessing multiple entries at once. The description... and writeToFile:atomically: methods cause a dictionary to write a representation of itself to a string or to a file, respectively.




Adopted Protocols


NSCoding
- encodeWithCoder:
- initWithCoder:
NSCopying
- copyWithZone:
NSMutableCopying
- mutableCopyWithZone:


Method Types


Creating dictionaries
+ dictionary
+ dictionaryWithContentsOfFile:
+ dictionaryWithContentsOfURL:
+ dictionaryWithDictionary:
+ dictionaryWithObject:forKey:
+ dictionaryWithObjects:forKeys:
+ dictionaryWithObjects:forKeys:count:
+ dictionaryWithObjectsAndKeys:
- initWithContentsOfFile:
- initWithContentsOfURL:
- initWithDictionary:
- initWithDictionary:copyItems:
- initWithObjects:forKeys:
- initWithObjects:forKeys:count:
- initWithObjectsAndKeys:
Counting entries
- count
Accessing keys and values
- allKeys
- allKeysForObject:
- allValues
- description
- descriptionInStringsFileFormat
- descriptionWithLocale:
- descriptionWithLocale:indent:
- keyEnumerator
- keysSortedByValueUsingSelector:
- objectEnumerator
- objectForKey:
- objectsForKeys:notFoundMarker:
Storing dictionaries
- writeToFile:atomically:
- writeToURL:atomically:
Accessing file attributes
- fileGroupOwnerAccountName
- fileModificationDate
- fileOwnerAccountName
- filePosixPermissions
- fileSize
- fileSystemFileNumber
- fileSystemNumber
- fileType


Class Methods



dictionary

+ (id)dictionary

Creates and returns an empty dictionary. This method is declared primarily for the use with mutable subclasses of NSDictionary.

If you don't want a temporary object, you can also create an empty dictionary using alloc... and init.



dictionaryWithContentsOfFile:

+ (id)dictionaryWithContentsOfFile:(NSString *)path

Allocates and initializes a dictionary using the keys and values found in path. path can be a full or relative pathname. The file identified by path must contain a string representation of a property list whose root object is a dictionary. The dictionary must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects).

This method returns nil if there is a file error or if the contents of the file are an invalid representation of a dictionary.

See Also: - initWithContentsOfFile:



dictionaryWithContentsOfURL:

+ (id)dictionaryWithContentsOfURL:(NSURL *)anURL

Description forthcoming.

dictionaryWithDictionary:

+ (id)dictionaryWithDictionary:(NSDictionary *)otherDictionary

Creates and returns a dictionary containing the keys and values found in otherDictionary.

See Also: - initWithDictionary:



dictionaryWithObject:forKey:

+ (id)dictionaryWithObject:(id)anObject forKey:(id)aKey

Creates and returns a dictionary containing a single object, anObject, for a single key, aKey.

See Also: + dictionaryWithObjects:forKeys:, + dictionaryWithObjects:forKeys:count:, + dictionaryWithObjectsAndKeys:



dictionaryWithObjects:forKeys:

+ (id)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys

Creates and returns a dictionary containing entries constructed from the contents of objects and keys. This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. Each value object receives a retain message before being added to the dictionary. In contrast, each key is copied (using copyWithZone:; keys must conform to the NSCopying protocol), and the copy is added to the dictionary. An NSInvalidArgumentException is raised if objects and keys don't have the same number of elements.

See Also: - initWithObjects:forKeys:, + dictionaryWithObject:forKey:, + dictionaryWithObjects:forKeys:count:, + dictionaryWithObjectsAndKeys:



dictionaryWithObjects:forKeys:count:

+ (id)dictionaryWithObjects:(id *)objects forKeys:(id *)keys count:(unsigned)count

Creates and returns a dictionary containing count objects from the objects array. The objects are associated with keys taken from the keys array. For example, this code excerpt creates a dictionary that associates the alphabetic characters with their ASCII values:

static const int N_ENTRIES = 26;
NSDictionary *asciiDict;
NSString *keyArray[N_ENTRIES];
NSNumber *valueArray[N_ENTRIES];
int i;

for (i = 0; i < N_ENTRIES; i++) {
    char charValue = 'a' + i;
    keyArray[i] = [NSString stringWithFormat:@"%c", charValue];
    valueArray[i] = [NSNumber numberWithChar:charValue];
}
	
asciiDict = [NSDictionary dictionaryWithObjects:(id *)valueArray 
    forKeys:(id *)keyArray count:N_ENTRIES];

See Also: - initWithObjects:forKeys:count:, + dictionaryWithObject:forKey:, + dictionaryWithObjects:forKeys:, + dictionaryWithObjectsAndKeys:



dictionaryWithObjectsAndKeys:

+ (id)dictionaryWithObjectsAndKeys:(id)firstObject, ...

Creates and returns a dictionary containing entries constructed from the specified set of objects and keys. dictionaryWithObjectsAndKeys: takes a variable number of arguments: a null-terminated list of alternating objects and keys. If any key is nil, an NSInvalidArgumentException is raised.

This method is similar to dictionaryWithObjects:forKeys:, differing only in the way key-value pairs are specified.

See Also: - initWithObjectsAndKeys:, + dictionaryWithObject:forKey:, + dictionaryWithObjects:forKeys:, + dictionaryWithObjects:forKeys:count:




Instance Methods



allKeys

- (NSArray *)allKeys

Returns a new array containing the dictionary's keys or an empty array if the dictionary has no entries. The order of the elements in the array isn't defined.

See Also: - allValues, - allKeysForObject:



allKeysForObject:

- (NSArray *)allKeysForObject:(id)anObject

Finds all occurrences of the value anObject in the dictionary and returns a new array with the corresponding keys. Each object in the dictionary is sent an isEqual: message to determine if it's equal to anObject. If no object matching anObject is found, this method returns nil.

See Also: - allKeys, - keyEnumerator



allValues

- (NSArray *)allValues

Returns a new array containing the dictionary's values, or an empty array if the dictionary has no entries. The order of the values in the array isn't defined.

See Also: - allKeys, - objectEnumerator



count

- (unsigned)count

Returns the number of entries in the dictionary.



description

- (NSString *)description

Returns a string that represents the contents of the receiver, formatted as a property list. If each key in the dictionary responds to compare:, the entries are listed in ascending order, by key. Otherwise, the order in which the entries are listed is undefined.

See Also: - descriptionWithLocale:, - descriptionWithLocale:indent:



descriptionInStringsFileFormat

- (NSString *)descriptionInStringsFileFormat

Returns a string that represents the contents of the receiver, formatted in .strings file format. The order in which the entries are listed is undefined.



descriptionWithLocale:

- (NSString *)descriptionWithLocale:(NSDictionary *)locale

Returns a string object that represents the contents of the receiver, formatted as a property list. locale specifies options used for formatting each of the receiver's keys and values; specify nil if you don't want them formatted.

For a description of how locale is applied to each element in the receiver, see descriptionWithLocale:indent:.

If each key in the dictionary responds to compare:, the entries are listed in ascending order, by key. Otherwise, the order in which the entries are listed is undefined.

See Also: - description, - descriptionWithLocale:indent:



descriptionWithLocale:indent:

- (NSString *)descriptionWithLocale:(NSDictionary *)locale indent:(unsigned)level

Returns a string object that represents the contents of the receiver, formatted as a property list. Use locale to specify options to be passed to the methods that format each of the receiver's keys and values; specify nil if you don't want them formatted. level allows you to specify a level of indent, to make the output more readable: set level to 0 to use four spaces to indent, or 1 to indent the output with a tab character.

The returned NSString contains the string representations of each of the receiver's entries. descriptionWithLocale:indent: obtains the string representation of a given key or value as follows:

If each key in the dictionary responds to compare:, the entries are listed in ascending order, by key. Otherwise, the order in which the entries are listed is undefined.

See Also: - description, - descriptionWithLocale:



fileGroupOwnerAccountName

- (NSString *)fileGroupOwnerAccountName

Returns the object for the key NSFileGroupOwnerAccountName or nil if the receiver doesn't have an entry for the key.

This and the other file... methods are for use with a dictionary such as those returned from the methods fileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes (NSDirectoryEnumerator) and fileAttributes (NSDirectoryEnumerator) that represents the POSIX attributes of a file or directory. This method returns the name of the corresponding file's group.



fileModificationDate

- (NSDate *)fileModificationDate

Returns the object for the key NSFileModificationDate or nil if the receiver doesn't have an entry for the key.

This and the other file... methods are for use with a dictionary such as those returned from the methods fileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes (NSDirectoryEnumerator) and fileAttributes (NSDirectoryEnumerator) that represents the POSIX attributes of a file or directory. This method returns the date that the file's data was last modified.



fileOwnerAccountName

- (NSString *)fileOwnerAccountName

Returns the object for the key NSFileOwnerAccountName or nil if the receiver doesn't have an entry for the key.

This and the other file... methods are for use with a dictionary such as those returned from the methods fileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes (NSDirectoryEnumerator) and fileAttributes (NSDirectoryEnumerator) that represents the POSIX attributes of a file or directory. This method returns the account name of the file's owner.



filePosixPermissions

- (unsigned long)filePosixPermissions

Returns the object for the key NSFilePosixPermissions or nil if the receiver doesn't have an entry for the key.

This and the other file... methods are for use with a dictionary such as those returned from the methods fileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes (NSDirectoryEnumerator) and fileAttributes (NSDirectoryEnumerator) that represents the POSIX attributes of a file or directory. This method returns the file's permissions.



fileSize

- (unsigned long long)fileSize

Returns the object for the key NSFileSize or nil if the receiver doesn't have an entry for the key.

This and the other file... methods are for use with a dictionary such as those returned from the methods fileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes (NSDirectoryEnumerator) and fileAttributes (NSDirectoryEnumerator) that represents the POSIX attributes of a file or directory. This method returns the file's size.



fileSystemFileNumber

- (unsigned long)fileSystemFileNumber

Returns the object for the key NSFileSystemFileNumber or nil if the receiver doesn't have an entry for the key.

This and the other file... methods are for use with a dictionary such as those returned from the methods fileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes (NSDirectoryEnumerator) and fileAttributes (NSDirectoryEnumerator) that represents the POSIX attributes of a file or directory. This method returns the file's inode.



fileSystemNumber

- (unsigned long)fileSystemNumber

Returns the object for the key NSFileSystemNumber or nil if the receiver doesn't have an entry for the key.

This and the other file... methods are for use with a dictionary such as those returned from the methods fileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes (NSDirectoryEnumerator) and fileAttributes (NSDirectoryEnumerator) that represents the POSIX attributes of a file or directory. This method returns the ID of the device containing the file.



fileType

- (NSString *)fileType

Returns the object for the key NSFileType or nil if the receiver doesn't have an entry for the key.

This and the other file... methods are for use with a dictionary such as those returned from the methods fileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes (NSDirectoryEnumerator) and fileAttributes (NSDirectoryEnumerator) that represents the POSIX attributes of a file or directory. This method returns the file's type, which is one of the following:


String Meaning
NSFileTypeUnknown Unknown file type
NSFileTypeCharacterSpecial Character special file
NSFileTypeDirectory Directory
NSFileTypeBlockSpecial Block special file
NSFileTypeRegular Regular file
NSFileTypeSymbolicLink Symbolic link
NSFileTypeSocket Socket



initWithContentsOfFile:

- (id)initWithContentsOfFile:(NSString *)path

Initializes a newly allocated dictionary using the keys and values found in path. path can be a full or relative pathname. The file identified by path must contain a string representation of a property list whose root object is a dictionary. The dictionary must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects).

After initializing the receiver, this method returns self. However, if the new instance can't be initialized (either because of a file error or because the contents of the file is an invalid representation of a dictionary), it's deallocated and nil is returned.

See Also: + dictionaryWithContentsOfFile:



initWithContentsOfURL:

- (id)initWithContentsOfURL:(NSURL *)anURL

Description forthcoming.

initWithDictionary:

- (id)initWithDictionary:(NSDictionary *)otherDictionary

Initializes a newly allocated dictionary by placing in it the keys and values contained in otherDictionary. Returns self.

See Also: + dictionaryWithDictionary:



initWithDictionary:copyItems:

- (id)initWithDictionary:(NSDictionary *)otherDictionary copyItems:(BOOL)flag

Initializes a newly allocated dictionary and, if flag is NO, places in it the objects contained in otherDictionary. If flag is YES, the members of otherDictionary are copied, and the copies are added to the receiver. Note that copyWithZone: is used to make the copies. Thus, the receiver's new member objects may be immutable, even though their counterparts in otherDictionary were mutable. Also, members must conform to the NSCopying protocol. Returns self.

See Also: - initWithDictionary:



initWithObjects:forKeys:

- (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys

Initializes a newly allocated dictionary with entries constructed from the contents of the objects and keys arrays. This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. Each value object receives a retain message before being added to the dictionary. In contrast, each key object is copied (using copyWithZone:), and the copy is added to the dictionary. An NSInvalidArgumentException is raised if the objects and keys arrays do not have the same number of elements.

See Also: + dictionaryWithObjects:forKeys:, - initWithObjects:forKeys:count:, - initWithObjectsAndKeys:



initWithObjects:forKeys:count:

- (id)initWithObjects:(id *)objects forKeys:(id *)keys count:(unsigned)count

Initializes a newly allocated dictionary with count entries. This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. Each value object receives a retain message before being added to the dictionary. In contrast, each key object is copied (using copyWithZone:), and the copy is added to the dictionary. An NSInvalidArgumentException is raised if a key or value object is nil.

See Also: + dictionaryWithObjects:forKeys:count:, - initWithObjects:forKeys:, - initWithObjectsAndKeys:



initWithObjectsAndKeys:

- (id)initWithObjectsAndKeys:(id)firstObject, ...

Initializes a newly allocated dictionary with entries constructed from the specified set of objects and keys. initWithObjectsAndKeys: takes a variable number of arguments: a null-terminated list of alternating objects and keys. If a key is found to be nil , an NSInvalidArgumentException is raised.

This method is similar to initWithObjects:forKeys:, differing only in the way in which the key-value pairs are specified.

See Also: + dictionaryWithObjectsAndKeys:, - initWithObjects:forKeys:, - initWithObjects:forKeys:count:



isEqualToDictionary:

- (BOOL)isEqualToDictionary:(NSDictionary *)otherDictionary

Compares the receiving dictionary to otherDictionary. If the contents of otherDictionary are equal to the contents of the receiver, this method returns YES. If not, it returns NO.

Two dictionaries have equal 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.

See Also: isEqual: (NSObject protocol)



keyEnumerator

- (NSEnumerator *)keyEnumerator

Returns an enumerator object that lets you access each key in the dictionary:

NSEnumerator *enumerator = [myDictionary keyEnumerator];
id key;
	
while ((key = [enumerator nextObject])) {
    /* code that uses the returned key */ 
}

When this method is used with mutable subclasses of NSDictionary, your code shouldn't modify the entries during enumeration. If you intend to modify the entries, use the allKeys method to create a "snapshot" of the dictionary's keys. Then use this snapshot to traverse the entries, modifying them along the way.

Note that the objectEnumerator method provides a convenient way to access each value in the dictionary.

See Also: - allKeys, - allKeysForObject:, - objectEnumerator, nextObject (NSEnumerator)



keysSortedByValueUsingSelector:

- (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator

Returns an array of the dictionary's keys, in the order they would be in if the dictionary was sorted by its values. Pairs of dictionary values are compared using the comparison method specified by comparator; the comparator message is sent to one of the values, and has as its single argument the other value from the dictionary. The comparator method should return NSOrderedAscending if the receiver is smaller than the argument, NSOrderedDescending if the receiver is larger than the argument, and NSOrderedSame if they are equal.

See Also: - allKeys, - sortedArrayUsingSelector: (NSArray)



objectEnumerator

- (NSEnumerator *)objectEnumerator

Returns an enumerator object that lets you access each value in the dictionary:

NSEnumerator *enumerator = [myDictionary objectEnumerator];
id value;
	
while ((value = [enumerator nextObject])) {
    /* code that acts on the dictionary's values */ 
}

When this method is used with mutable subclasses of NSDictionary, your code shouldn't modify the entries during enumeration. If you intend to modify the entries, use the allValues method to create a "snapshot" of the dictionary's values. Work from this snapshot to modify the values.

See Also: - keyEnumerator, - nextObject (NSEnumerator)



objectForKey:

- (id)objectForKey:(id)aKey

Returns an entry's value given its key, or nil if no value is associated with aKey.

See Also: - allKeys, - allValues



objectsForKeys:notFoundMarker:

- (NSArray *)objectsForKeys:(NSArray *)keys notFoundMarker:(id)anObject

Returns the set of objects from the receiver that correspond to the specified keys as an NSArray. The objects in the returned array and the keys array have a one-for-one correspondence, so that the nth object in the returned array corresponds to the nth key in keys. If an object isn't found in the receiver to correspond to a given key, the marker object, specified by anObject, is placed in the corresponding element of the returned array.



writeToFile:atomically:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Writes a textual description of the contents of the dictionary to path. If the receiver's contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the file written by this method can be used to initialize a new dictionary with the class method dictionaryWithContentsOfFile: or the instance method initWithContentsOfFile:.

If flag is YES, the dictionary is written to an auxiliary file, and then the auxiliary file is renamed to path. If flag is NO, the dictionary is written directly to path. The YES option guarantees that path, if it exists at all, won't be corrupted even if the system should crash during writing.

If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

This method returns YES if the file is written successfully, and NO otherwise.



writeToURL:atomically:

- (BOOL)writeToURL:(NSURL *)anURL atomically:(BOOL)flag

Writes a textual description of the contents of the dictionary to anURL. If the receiver's contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the location written by this method can be used to initialize a new dictionary with the class method dictionaryWithContentsOfURL: or the instance method initWithContentsOfURL:.

If flag is YES, the dictionary is written to an auxiliary location, and then the auxiliary location is renamed to anURL. If flag is NO, the dictionary is written directly to anURL. The YES option guarantees that anURL, if it exists at all, won't be corrupted even if the system should crash during writing. flag is ignored if anURL of a type that cannot be written atomically.

This method returns YES if the location is written successfully, and NO otherwise.




Table of Contents