Class

NSDictionary

A static collection of objects associated with unique keys.

Declaration

@interface NSDictionary<__covariant KeyType, __covariant ObjectType> : NSObject

Overview

The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. For example, an interactive form could be represented as a dictionary, with the field names as keys, corresponding to user-entered 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 Accessing Object Properties). 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.

Creating NSDictionary Objects Using Dictionary Literals

In addition to the provided initializers, such as initWithObjects:forKeys:, you can create an NSDictionary object using a dictionary literal.

NSDictionary *dictionary = @{
       @"anObject" : someObject,
    @"helloString" : @"Hello, World!",
    @"magicNumber" : @42,
         @"aValue" : someValue
};

In Objective-C, the compiler generates code that makes an underlying call to the dictionaryWithObjects:forKeys:count: method.

id objects[] = { someObject, @"Hello, World!", @42, someValue };
id keys[] = { @"anObject", @"helloString", @"magicNumber", @"aValue" };
NSUInteger count = sizeof(objects) / sizeof(id);
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
                                                       forKeys:keys
                                                         count:count];

Unlike dictionaryWithObjectsAndKeys: and other initializers, dictionary literals specify entries in key-value order. You should not terminate the list of objects with nil when using this literal syntax, and in fact nil is an invalid value. For more information about object literals in Objective-C, see Working with Objects in Programming with Objective-C.

In Swift, the NSDictionary class conforms to the DictionaryLiteralConvertible protocol, which allows it to be initialized with dictionary literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).

Accessing Values Using Subscripting

In addition to the provided instance methods, such as objectForKey:, you can access NSDictionary values by their keys using subscripting.

id value = dictionary[@"helloString"];

Enumerating Entries Using for-in Loops

In addition to the provided instance methods, such as enumerateKeysAndObjectsUsingBlock:, you can enumerate NSDictionary entries using for-in loops.

for (NSString *key in dictionary) {
    id value = dictionary[key];
    NSLog(@"Value: %@ for key: %@", value, key);
}

In Objective-C, NSDictionary conforms to the NSFastEnumeration protocol.

In Swift, NSDictionary conforms to the SequenceType protocol.

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. 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.

Topics

Creating an Empty Dictionary

dictionary

Creates an empty dictionary.

init

Initializes a newly allocated dictionary.

Creating a Dictionary from Objects and Keys

dictionaryWithObjects:forKeys:

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

dictionaryWithObjects:forKeys:count:

Creates a dictionary containing a specified number of objects from a C array.

initWithObjects:forKeys:

Initializes a newly allocated dictionary with key-value pairs constructed from the provided arrays of keys and objects.

initWithObjects:forKeys:count:

Initializes a newly allocated dictionary with the specified number of key-value pairs constructed from the provided C arrays of keys and objects.

dictionaryWithObjectsAndKeys:

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

initWithObjectsAndKeys:

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

dictionaryWithObject:forKey:

Creates a dictionary containing a given key and value.

Creating a Dictionary from Another Dictionary

dictionaryWithDictionary:

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

initWithDictionary:

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

initWithDictionary:copyItems:

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

Creating a Dictionary from an External Source

dictionaryWithContentsOfURL:error:

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

dictionaryWithContentsOfURL:

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

Deprecated
initWithContentsOfURL:error:

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

initWithContentsOfURL:

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

Deprecated
dictionaryWithContentsOfFile:

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

Deprecated
initWithContentsOfFile:

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

Deprecated

Creating a Dictionary from an NSCoder

initWithCoder:

Creates a dictionary initialized from data in the provided unarchiver.

Creating Key Sets for Shared-Key Optimized Dictionaries

sharedKeySetForKeys:

Creates a shared key set object for the specified keys.

Counting Entries

count

The number of entries in the dictionary.

Comparing Dictionaries

isEqualToDictionary:

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

Accessing Keys and Values

allKeys

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

allKeysForObject:

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

allValues

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

valueForKey:

Returns the value associated with a given key.

getObjects:andKeys:count:

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

getObjects:andKeys:

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

Deprecated
objectsForKeys:notFoundMarker:

Returns as a static array the set of objects from the dictionary that corresponds to the specified keys.

objectForKey:

Returns the value associated with a given key.

objectForKeyedSubscript:

Returns the value associated with a given key.

Enumerating Dictionaries

keyEnumerator

Provides an enumerator to access the keys in the dictionary.

objectEnumerator

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

enumerateKeysAndObjectsUsingBlock:

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

enumerateKeysAndObjectsWithOptions:usingBlock:

Applies a given block object to the entries of the dictionary, with options specifying how the enumeration is performed.

countByEnumeratingWithState:objects:count:

Returns by reference a C array of objects over which the sender should iterate.

Sorting Dictionaries

keysSortedByValueUsingSelector:

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

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.

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.

Filtering Dictionaries

keysOfEntriesPassingTest:

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

keysOfEntriesWithOptions:passingTest:

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

Storing Dictionaries

writeToURL:error:

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

writeToURL:atomically:

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

Deprecated
writeToFile:atomically:

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

Deprecated

Accessing File Attributes

These convenience methods are for use with dictionaries returned by the NSFileManager method attributesOfItemAtPath:error:, and allow you to access POSIX and HFS attributes for files and directories.

fileSize

Returns the file’s size, in bytes.

fileType

Returns the file type.

fileCreationDate

Returns the file’s creation date.

fileModificationDate

Returns file’s modification date.

filePosixPermissions

Returns the file’s POSIX permissions.

fileOwnerAccountID

Returns the file’s owner account ID.

fileOwnerAccountName

Returns the file’s owner account name.

fileGroupOwnerAccountID

Returns file’s group owner account ID.

fileGroupOwnerAccountName

Returns the file’s group owner account name.

fileExtensionHidden

Returns a Boolean value indicating whether the file hides its extension.

fileIsImmutable

Returns a Boolean value indicating whether the file is immutable.

fileIsAppendOnly

Returns a Boolean value indicating whether the file is append only.

fileSystemFileNumber

Returns the filesystem file number.

fileSystemNumber

Returns the filesystem number.

fileHFSTypeCode

Returns file’s HFS type code.

fileHFSCreatorCode

Returns the file’s HFS creator code.

Describing a Dictionary

description

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

descriptionInStringsFileFormat

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

descriptionWithLocale:

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

descriptionWithLocale:indent:

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

See Also

Basic Collections

NSArray

A static ordered collection of objects.

NSMutableArray

A dynamic ordered collection of objects.

NSMutableDictionary

A dynamic collection of objects associated with unique keys.

NSSet

A static unordered collection of unique objects.

NSMutableSet

A dynamic unordered collection of unique objects.