NSDictionary Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in iOS 2.0 and later.
Declared in
NSDictionary.h
NSFileManager.h
NSKeyValueCoding.h
Companion guides
Related sample code

Overview

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. NSDictionary creates static dictionaries, and NSMutableDictionary creates dynamic dictionaries. (For convenience, the term dictionary refers 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 that 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:). In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see “Key-Value Coding Fundamentals”). Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull.

NSDictionary is “toll-free bridged” with its Core Foundation counterpart, CFDictionaryRef. See “Toll-Free Bridging” for more information on toll-free bridging.

Subclassing Notes

You generally shouldn’t need to subclass NSDictionary. Custom behavior can usually be achieved through composition rather than subclassing.

Methods to Override

If you do need to subclass NSDictionary, take into account that it is a class cluster. Any subclass must override the following primitive methods:

The other methods of NSDictionary operate by invoking one or more of these primitives. The non-primitive methods provide convenient ways of accessing multiple entries at once.

Alternatives to Subclassing

Before making a custom class of NSDictionary, investigate NSMapTable and the corresponding Core Foundation type, CFDictionary Reference. Because NSDictionary and CFDictionary are “toll-free bridged,” you can substitute a CFDictionary object for a NSDictionary object in your code (with appropriate casting). Although they are corresponding types, CFDictionary and NSDictionary do not have identical interfaces or implementations, and you can sometimes do things with CFDictionary that you cannot easily do with NSDictionary.

If the behavior you want to add supplements that of the existing class, you could write a category on NSDictionary. Keep in mind, however, that this category will be in effect for all instances of NSDictionary that you use, and this might have unintended consequences. Alternatively, you could use composition to achieve the desired behavior.

Adopted Protocols

NSCoding
NSCopying
NSMutableCopying
NSFastEnumeration

Tasks

Creating a Dictionary

Initializing an NSDictionary Instance

Creating Key Sets for Shared-Key Optimized Dictionaries

Counting Entries

Comparing Dictionaries

Accessing Keys and Values

Enumerating Dictionaries

Sorting Dictionaries

Filtering Dictionaries

Storing Dictionaries

Accessing File Attributes

Creating a Description

Class Methods

dictionary

Creates and returns an empty dictionary.

+ (instancetype)dictionary
Return Value

A new empty dictionary.

Discussion

This method is declared primarily for 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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

dictionaryWithContentsOfFile:

Creates and returns a dictionary using the keys and values found in a file specified by a given path.

+ (id)dictionaryWithContentsOfFile:(NSString *)path
Parameters
path

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.

Return Value

A new dictionary that contains the dictionary at path, or nil if there is a file error or if the contents of the file are an invalid representation of a dictionary.

Discussion

The dictionary representation in the file identified by path must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

dictionaryWithContentsOfURL:

Creates and returns a dictionary using the keys and values found in a resource specified by a given URL.

+ (id)dictionaryWithContentsOfURL:(NSURL *)aURL
Parameters
aURL

An URL that identifies a resource containing a string representation of a property list whose root object is a dictionary.

Return Value

A new dictionary that contains the dictionary at aURL, or nil if there is an error or if the contents of the resource are an invalid representation of a dictionary.

Discussion

The dictionary representation in the file identified by path must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSDictionary.h

dictionaryWithDictionary:

Creates and returns a dictionary containing the keys and values from another given dictionary.

+ (instancetype)dictionaryWithDictionary:(NSDictionary *)otherDictionary
Parameters
otherDictionary

A dictionary containing the keys and values with which to initialize the new dictionary.

Return Value

A new dictionary containing the keys and values found in otherDictionary.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

dictionaryWithObject:forKey:

Creates and returns a dictionary containing a given key and value.

+ (instancetype)dictionaryWithObject:(id)anObject forKey:(id<NSCopying>)aKey
Parameters
anObject

The value corresponding to aKey.

If this value is nil, an NSInvalidArgumentException is raised.

aKey

The key for anObject.

If this value is nil, an NSInvalidArgumentException is raised.

Return Value

A new dictionary containing a single object, anObject, for a single key, aKey.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

dictionaryWithObjects:forKeys:

Creates and returns a dictionary containing entries constructed from the contents of an array of keys and an array of values.

+ (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys
Parameters
objects

An array containing the values for the new dictionary.

keys

An array containing the keys for the new dictionary. Each key is copied (using copyWithZone:; keys must conform to the NSCopying protocol), and the copy is added to the dictionary.

Return Value

A new dictionary containing entries constructed from the contents of objects and keys.

Discussion

This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. An NSInvalidArgumentException is raised if objects and keys don’t have the same number of elements.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

dictionaryWithObjects:forKeys:count:

Creates and returns a dictionary containing count objects from the objects array.

+ (instancetype)dictionaryWithObjects:(const id [])objects forKeys:(const id<NSCopying> [])keys count:(NSUInteger)count
Parameters
objects

A C array of values for the new dictionary.

keys

A C array of keys for the new dictionary. Each key is copied (using copyWithZone:; keys must conform to the NSCopying protocol), and the copy is added to the new dictionary.

count

The number of elements to use from the keys and objects arrays. count must not exceed the number of elements in objects or keys.

Discussion

This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. An NSInvalidArgumentException is raised if a key or value object is nil.

The following code fragment illustrates how to create a dictionary that associates the alphabetic characters with their ASCII values:

static const NSInteger N_ENTRIES = 26;
NSDictionary *asciiDict;
NSString *keyArray[N_ENTRIES];
NSNumber *valueArray[N_ENTRIES];
NSInteger 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];
Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

dictionaryWithObjectsAndKeys:

Creates and returns a dictionary containing entries constructed from the specified set of values and keys.

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

The first value to add to the new dictionary.

...

First the key for firstObject, then a null-terminated list of alternating values and keys. If any key is nil, an NSInvalidArgumentException is raised.

Discussion

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

For example:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    @"value1", @"key1", @"value2", @"key2", nil];
Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

sharedKeySetForKeys:

Creates a shared key set object for the specified keys.

+ (id)sharedKeySetForKeys:(NSArray *)keys
Parameters
keys

The array of keys. If the parameter is nil, an exception is thrown. If the array of keys is empty, an empty key set is returned.

Return Value

A shared key set object.

Discussion

The array of keys may contain duplicates which are quietly ignored. Duplicate hash values of the keys are quietly allowed, but may cause lower performance and increase memory usage.

Typically you would create a shared key set for a given set of keys once, before creating shared key dictionaries, and retain and save the result of this method for use with the NSMutableDictionary class method dictionaryWithSharedKeySet:.

Availability
  • Available in iOS 6.0 and later.
Declared In
NSDictionary.h

Instance Methods

allKeys

Returns a new array containing the dictionary’s keys.

- (NSArray *)allKeys
Return Value

A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries.

Discussion

The order of the elements in the array is not defined.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

allKeysForObject:

Returns a new array containing the keys corresponding to all occurrences of a given object in the dictionary.

- (NSArray *)allKeysForObject:(id)anObject
Parameters
anObject

The value to look for in the dictionary.

Return Value

A new array containing the keys corresponding to all occurrences of anObject in the dictionary. If no object matching anObject is found, returns an empty array.

Discussion

Each object in the dictionary is sent an isEqual: message to determine if it’s equal to anObject.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

allValues

Returns a new array containing the dictionary’s values.

- (NSArray *)allValues
Return Value

A new array containing the dictionary’s values, or an empty array if the dictionary has no entries.

Discussion

The order of the values in the array isn’t defined.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

count

Returns the number of entries in the dictionary.

- (NSUInteger)count
Return Value

The number of entries in the dictionary.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSDictionary.h

description

Returns a string that represents the contents of the dictionary, formatted as a property list.

- (NSString *)description
Return Value

A string that represents the contents of the dictionary, formatted as a property list.

Discussion

If each key in the dictionary is an NSString object, the entries are listed in ascending order by key, otherwise the order in which the entries are listed is undefined. This method is intended to produce readable output for debugging purposes, not for serializing data. If you want to store dictionary data for later retrieval, see Property List Programming Guide and Archives and Serializations Programming Guide.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

descriptionInStringsFileFormat

Returns a string that represents the contents of the dictionary, formatted in .strings file format.

- (NSString *)descriptionInStringsFileFormat
Return Value

A string that represents the contents of the dictionary, formatted in .strings file format.

Discussion

The order in which the entries are listed is undefined.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

descriptionWithLocale:

Returns a string object that represents the contents of the dictionary, formatted as a property list.

- (NSString *)descriptionWithLocale:(id)locale
Parameters
locale

An object that specifies options used for formatting each of the dictionary’s keys and values; pass nil if you don’t want them formatted.

On iOS and OS X v10.5 and later, either an instance of NSDictionary or an NSLocale object may be used for locale. On OS X v10.4 and earlier it must be an instance of NSDictionary.

Discussion

For a description of how locale is applied to each element in the dictionary, 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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

descriptionWithLocale:indent:

Returns a string object that represents the contents of the dictionary, formatted as a property list.

- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
Parameters
locale

An object that specifies options used for formatting each of the dictionary’s keys and values; pass nil if you don’t want them formatted.

On iOS and OS X v10.5 and later, either an instance of NSDictionary or an NSLocale object may be used for locale. On OS X v10.4 and earlier it must be an instance of NSDictionary.

level

Specifies a level of indentation, to make the output more readable: the indentation is (4 spaces) * level.

Return Value

A string object that represents the contents of the dictionary, formatted as a property list.

Discussion

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

  • If the object is an NSString object, it is used as is.

  • If the object responds to descriptionWithLocale:indent:, that method is invoked to obtain the object’s string representation.

  • If the object responds to descriptionWithLocale:, that method is invoked to obtain the object’s string representation.

  • If none of the above conditions is met, the object’s string representation is obtained by invoking its description method.

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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

enumerateKeysAndObjectsUsingBlock:

Applies a given block object to the entries of the dictionary.

- (void)enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block
Parameters
block

A block object to operate on entries in the dictionary.

Discussion

If the block sets *stop to YES, the enumeration stops.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSDictionary.h

enumerateKeysAndObjectsWithOptions:usingBlock:

Applies a given block object to the entries of the dictionary.

- (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id key, id obj, BOOL *stop))block
Parameters
opts

Enumeration options.

block

A block object to operate on entries in the dictionary.

Discussion

If the block sets *stop to YES, the enumeration stops.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSDictionary.h

fileCreationDate

Returns the value for the NSFileCreationDate key.

- (NSDate *)fileCreationDate
Return Value

The value for the NSFileCreationDate key, or nil if the dictionary doesn’t have an entry for the key.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileExtensionHidden

Returns the value for the NSFileExtensionHidden key.

- (BOOL)fileExtensionHidden
Return Value

The value for the NSFileExtensionHidden key, or NO if the dictionary doesn’t have an entry for the key.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileGroupOwnerAccountID

Returns the value for the NSFileGroupOwnerAccountID key.

- (NSNumber *)fileGroupOwnerAccountID
Return Value

The value for the NSFileGroupOwnerAccountID key, or nil if the dictionary doesn’t have an entry for the key.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileGroupOwnerAccountName

Returns the value for the NSFileGroupOwnerAccountName key.

- (NSString *)fileGroupOwnerAccountName
Return Value

The value for the key NSFileGroupOwnerAccountName, or nil if the dictionary doesn’t have an entry for the key.

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileHFSCreatorCode

Returns the value for the NSFileHFSCreatorCode key.

- (OSType)fileHFSCreatorCode
Return Value

The value for the NSFileHFSCreatorCode key, or 0 if the dictionary doesn’t have an entry for the key.

Discussion

See “HFS File Types” for details on the OSType data type.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileHFSTypeCode

Returns the value for the NSFileHFSTypeCode key.

- (OSType)fileHFSTypeCode
Return Value

The value for the NSFileHFSTypeCode key, or 0 if the dictionary doesn’t have an entry for the key.

Discussion

See “HFS File Types” for details on the OSType data type.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileIsAppendOnly

Returns the value for the NSFileAppendOnly key.

- (BOOL)fileIsAppendOnly
Return Value

The value for the NSFileAppendOnly key, or NO if the dictionary doesn’t have an entry for the key.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileIsImmutable

Returns the value for the NSFileImmutable key.

- (BOOL)fileIsImmutable
Return Value

The value for the NSFileImmutable key, or NO if the dictionary doesn’t have an entry for the key.

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileModificationDate

Returns the value for the key NSFileModificationDate.

- (NSDate *)fileModificationDate
Return Value

The value for the key NSFileModificationDate, or nil if the dictionary doesn’t have an entry for the key.

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSFileManager.h

fileOwnerAccountID

Returns the value for the NSFileOwnerAccountID key.

- (NSNumber *)fileOwnerAccountID
Return Value

The value for the NSFileOwnerAccountID key, or nil if the dictionary doesn’t have an entry for the key.

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileOwnerAccountName

Returns the value for the key NSFileOwnerAccountName.

- (NSString *)fileOwnerAccountName
Return Value

The value for the key NSFileOwnerAccountName, or nil if the dictionary doesn’t have an entry for the key.

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

filePosixPermissions

Returns the value for the key NSFilePosixPermissions.

- (NSUInteger)filePosixPermissions
Return Value

The value, as an unsigned long, for the key NSFilePosixPermissions, or 0 if the dictionary doesn’t have an entry for the key.

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileSize

Returns the value for the key NSFileSize.

- (unsigned long long)fileSize
Return Value

The value, as an unsigned long long, for the key NSFileSize, or 0 if the dictionary doesn’t have an entry for the key.

Discussion

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.

Special Considerations

If the file has a resource fork, the returned value does not include the size of the resource fork.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileSystemFileNumber

Returns the value for the key NSFileSystemFileNumber.

- (NSUInteger)fileSystemFileNumber
Return Value

The value, as an unsigned long, for the key NSFileSystemFileNumber, or 0 if the dictionary doesn’t have an entry for the key

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileSystemNumber

Returns the value for the key NSFileSystemNumber.

- (NSInteger)fileSystemNumber
Return Value

The value, as an unsigned long, for the key NSFileSystemNumber, or 0 if the dictionary doesn’t have an entry for the key

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

fileType

Returns the value for the key NSFileType.

- (NSString *)fileType
Return Value

The value for the key NSFileType, or nil if the dictionary doesn’t have an entry for the key.

Discussion

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. Possible return values are described in the “Constants” section of NSFileManager.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSFileManager.h

getObjects:andKeys:

Returns by reference C arrays of the keys and values in the dictionary.

- (void)getObjects:(id [])objects andKeys:(id [])keys
Parameters
objects

Upon return, contains a C array of the values in the dictionary.

keys

Upon return, contains a C array of the keys in the dictionary.

Discussion

The elements in the returned arrays are ordered such that the first element in objects is the value for the first key in keys and so on.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

init

Initializes a newly allocated dictionary.

- (instancetype)init
Return Value

A dictionary.

Discussion

This method is a designated initializer of NSDictionary.

Availability
  • Available in iOS 7.0 and later.
Declared In
NSDictionary.h

initWithContentsOfFile:

Initializes a newly allocated dictionary using the keys and values found in a file at a given path.

- (id)initWithContentsOfFile:(NSString *)path
Parameters
path

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.

Return Value

An initialized dictionary—which might be different than the original receiver—that contains the dictionary at path, or nil if there is a file error or if the contents of the file are an invalid representation of a dictionary.

Discussion

The dictionary representation in the file identified by path must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

initWithContentsOfURL:

Initializes a newly allocated dictionary using the keys and values found at a given URL.

- (id)initWithContentsOfURL:(NSURL *)aURL
Parameters
aURL

An URL that identifies a resource containing a string representation of a property list whose root object is a dictionary.

Return Value

An initialized dictionary—which might be different than the original receiver—that contains the dictionary at aURL, or nil if there is an error or if the contents of the resource are an invalid representation of a dictionary.

Discussion

The dictionary representation in the file identified by path must contain only property list objects (NSString, NSData, NSDate, NSNumber, NSArray, or NSDictionary objects). For more details, see Property List Programming Guide. The objects contained by this dictionary are immutable, even if the dictionary is mutable.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

initWithDictionary:

Initializes a newly allocated dictionary by placing in it the keys and values contained in another given dictionary.

- (instancetype)initWithDictionary:(NSDictionary *)otherDictionary
Parameters
otherDictionary

A dictionary containing the keys and values with which to initialize the new dictionary.

Return Value

An initialized dictionary—which might be different than the original receiver—containing the keys and values found in otherDictionary.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSDictionary.h

initWithDictionary:copyItems:

Initializes a newly allocated dictionary using the objects contained in another given dictionary.

- (instancetype)initWithDictionary:(NSDictionary *)otherDictionary copyItems:(BOOL)flag
Parameters
otherDictionary

A dictionary containing the keys and values with which to initialize the new dictionary.

flag

If YES, each object in otherDictionary receives a copyWithZone: message to create a copy of the object—objects must conform to the NSCopying protocol. In a managed memory environment, this is instead of the retain message the object would otherwise receive. The object copy is then added to the returned dictionary.

If NO, then in a managed memory environment each object in otherDictionary simply receives a retain message when it is added to the returned dictionary.

Return Value

An initialized object—which might be different than the original receiver—containing the keys and values found in otherDictionary.

Discussion

After an immutable dictionary has been initialized in this way, it cannot be modified.

The copyWithZone: method performs a shallow copy. If you have a collection of arbitrary depth, passing YES for the flag parameter will perform an immutable copy of the first level below the surface. If you pass NO the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

initWithObjects:forKeys:

Initializes a newly allocated dictionary with entries constructed from the contents of the objects and keys arrays.

- (instancetype)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys
Parameters
objects

An array containing the values for the new dictionary.

keys

An array containing the keys for the new dictionary. Each key is copied (using copyWithZone:; keys must conform to the NSCopying protocol), and the copy is added to the new dictionary.

Discussion

This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. An NSInvalidArgumentException is raised if the objects and keys arrays do not have the same number of elements.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

initWithObjects:forKeys:count:

Initializes a newly allocated dictionary with count entries.

- (instancetype)initWithObjects:(const id [])objects forKeys:(const id<NSCopying> [])keys count:(NSUInteger)count
Parameters
objects

A C array of values for the new dictionary.

keys

A C array of keys for the new dictionary. Each key is copied (using copyWithZone:; keys must conform to the NSCopying protocol), and the copy is added to the new dictionary.

count

The number of elements to use from the keys and objects arrays. count must not exceed the number of elements in objects or keys.

Discussion

This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes. An NSInvalidArgumentException is raised if a key or value object is nil.

This method is a designated initializer of NSDictionary.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

initWithObjectsAndKeys:

Initializes a newly allocated dictionary with entries constructed from the specified set of values and keys.

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

The first value to add to the new dictionary.

...

First the key for firstObject, then a null-terminated list of alternating values and keys. If any key is nil, an NSInvalidArgumentException is raised.

Discussion

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

For example:

NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
    @"value1", @"key1", @"value2", @"key2", nil];
Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

isEqualToDictionary:

Returns a Boolean value that indicates whether the contents of the receiving dictionary are equal to the contents of another given dictionary.

- (BOOL)isEqualToDictionary:(NSDictionary *)otherDictionary
Parameters
otherDictionary

The dictionary with which to compare the receiving dictionary.

Return Value

YES if the contents of otherDictionary are equal to the contents of the receiving dictionary, otherwise NO.

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
NSDictionary.h

keyEnumerator

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

- (NSEnumerator *)keyEnumerator
Return Value

An enumerator object that lets you access each key in the dictionary.

Discussion

The following code fragment illustrates how you might use this method.

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

If you use this method with instances of mutable subclasses of NSDictionary, your code should not 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.

Special Considerations

It is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Fast enumeration is available on OS X v10.5 and later and iOS 2.0 and later.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

keysOfEntriesPassingTest:

Returns the set of keys whose corresponding value satisfies a constraint described by a block object.

- (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate
Parameters
predicate

A block object that specifies constraints for values in the dictionary.

Return Value

The set of keys whose corresponding value satisfies predicate.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSDictionary.h

keysOfEntriesWithOptions:passingTest:

Returns the set of keys whose corresponding value satisfies a constraint described by a block object.

- (NSSet *)keysOfEntriesWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate
Parameters
opts

A bit mask of enumeration options.

predicate

A block object that specifies constraints for values in the dictionary.

Return Value

The set of keys whose corresponding value satisfies predicate.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSDictionary.h

keysSortedByValueUsingComparator:

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block.

- (NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr
Parameters
cmptr

A comparator block.

Return Value

An array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using cmptr.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSDictionary.h

keysSortedByValueUsingSelector:

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values.

- (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator
Parameters
comparator

A selector that specifies the method to use to compare the values in the dictionary.

The comparator method should return NSOrderedAscending if the dictionary value is smaller than the argument, NSOrderedDescending if the dictionary value is larger than the argument, and NSOrderedSame if they are equal.

Return Value

An array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values.

Discussion

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.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

keysSortedByValueWithOptions:usingComparator:

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block and a specified set of options.

- (NSArray *)keysSortedByValueWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr
Parameters
opts

A bitmask of sort options.

cmptr

A comparator block.

Return Value

An array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using cmptr with the options given in opts.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSDictionary.h

objectEnumerator

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

- (NSEnumerator *)objectEnumerator
Return Value

An enumerator object that lets you access each value in the dictionary.

Discussion

The following code fragment illustrates how you might use the method.

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

If you use this method with instances of mutable subclasses of NSDictionary, your code should not 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.

Special Considerations

It is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Fast enumeration is available on OS X v10.5 and later and iOS 2.0 and later.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
NSDictionary.h

objectForKey:

Returns the value associated with a given key.

- (id)objectForKey:(id)aKey
Parameters
aKey

The key for which to return the corresponding value.

Return Value

The value associated with aKey, or nil if no value is associated with aKey.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

objectForKeyedSubscript:

Returns the value associated with a given key.

- (id)objectForKeyedSubscript:(id)key
Parameters
key

The key for which to return the corresponding value.

Return Value

The value associated with aKey, or nil if no value is associated with aKey.

Discussion

This method behaves the same as objectForKey:.

Availability
  • Available in iOS 6.0 and later.
Declared In
NSDictionary.h

objectsForKeys:notFoundMarker:

Returns the set of objects from the dictionary that corresponds to the specified keys as an NSArray.

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

An NSArray containing the keys for which to return corresponding values.

anObject

The marker object to place in the corresponding element of the returned array if an object isn’t found in the dictionary to correspond to a given key.

Discussion

The objects in the returned array and the keys array have a one-for-one correspondence, so that the nthe object in the returned array corresponds to the nthe key in keys.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h

valueForKey:

Returns the value associated with a given key.

- (id)valueForKey:(NSString *)key
Parameters
key

The key for which to return the corresponding value. Note that when using key-value coding, the key must be a string (see “Key-Value Coding Fundamentals”).

Return Value

The value associated with key.

Discussion

If key does not start with “@”, invokes objectForKey:. If key does start with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
NSKeyValueCoding.h

writeToFile:atomically:

Writes a property list representation of the contents of the dictionary to a given path.

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

The path at which to write the file.

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

flag

A flag that specifies whether the file should be written atomically.

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.

Return Value

YES if the file is written successfully, otherwise NO.

Discussion

This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

If the dictionary’s contents are all property list 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:.

For more information about property lists, see Property List Programming Guide.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSDictionary.h

writeToURL:atomically:

Writes a property list representation of the contents of the dictionary to a given URL.

- (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag
Parameters
aURL

The URL to which to write the dictionary.

flag

A flag that specifies whether the output should be written atomically.

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

Return Value

YES if the location is written successfully, otherwise NO.

Discussion

This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant output would not be a valid property list.

If the dictionary’s contents are all property list 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:.

For more information about property lists, see Property List Programming Guide.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSDictionary.h