Class

NSDictionary

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

Overview

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, CFDictionary. 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 init(objects:forKeys:), you can create an NSDictionary object using a dictionary literal.

let dictionary: NSDictionary = [
    "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 3).

Accessing Values Using Subscripting

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

let value = dictionary["helloString"]

Enumerating Entries Using for-in Loops

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

for (key, value) in dictionary {
    print("Value: \(value) for key: \(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.

Symbols

Creating a Dictionary

init(object: Any, forKey: NSCopying)

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

Initializing an NSDictionary Instance

init()

Initializes a newly allocated dictionary.

init?(contentsOfFile: String)

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

init?(contentsOf: URL)

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

init(dictionary: [AnyHashable : Any])

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

init(dictionary: [AnyHashable : Any], copyItems: Bool)

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

init(objects: [Any], forKeys: [NSCopying])

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

init(objects: UnsafePointer<AnyObject>!, forKeys: UnsafePointer<NSCopying>!, count: Int)

Initializes a newly allocated dictionary with count entries.

Creating Key Sets for Shared-Key Optimized Dictionaries

class func sharedKeySet(forKeys: [NSCopying])

Creates a shared key set object for the specified keys.

Counting Entries

var count: Int

The number of entries in the dictionary

Comparing Dictionaries

func isEqual(to: [AnyHashable : Any])

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

var allKeys: [Any]

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

func allKeys(for: Any)

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

var allValues: [Any]

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

func object(forKey: Any)

Returns the value associated with a given key.

subscript(NSCopying)

Returns the value associated with a given key.

func objects(forKeys: [Any], notFoundMarker: Any)

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

func value(forKey: String)

Returns the value associated with a given key.

Enumerating Dictionaries

func objectEnumerator()

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

func enumerateKeysAndObjects((Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void)

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

Sorting Dictionaries

func keysSortedByValue(using: Selector)

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

func keysSortedByValue(comparator: (Any, Any) -> ComparisonResult)

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.

func keysSortedByValue(options: NSSortOptions = [], usingComparator: (Any, Any) -> ComparisonResult)

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

func keysOfEntries(passingTest: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool)

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

func keysOfEntries(options: NSEnumerationOptions = [], passingTest: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool)

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

Storing Dictionaries

func write(toFile: String, atomically: Bool)

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

func write(to: URL, atomically: Bool)

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

Accessing File Attributes

func fileCreationDate()

Returns the value for the NSFileCreationDate key.

func fileExtensionHidden()

Returns the value for the NSFileExtensionHidden key.

func fileGroupOwnerAccountID()

Returns the value for the NSFileGroupOwnerAccountID key.

func fileGroupOwnerAccountName()

Returns the value for the NSFileGroupOwnerAccountName key.

func fileHFSCreatorCode()

Returns the value for the NSFileHFSCreatorCode key.

func fileHFSTypeCode()

Returns the value for the NSFileHFSTypeCode key.

func fileIsAppendOnly()

Returns the value for the NSFileAppendOnly key.

func fileIsImmutable()

Returns the value for the NSFileImmutable key.

func fileModificationDate()

Returns the value for the key NSFileModificationDate.

func fileOwnerAccountID()

Returns the value for the NSFileOwnerAccountID key.

func fileOwnerAccountName()

Returns the value for the key NSFileOwnerAccountName.

func filePosixPermissions()

Returns the value for the key NSFilePosixPermissions.

func fileSize()

Returns the value for the key NSFileSize.

func fileSystemFileNumber()

Returns the value for the key NSFileSystemFileNumber.

func fileSystemNumber()

Returns the value for the key NSFileSystemNumber.

func fileType()

Returns the value for the key NSFileType.

Creating a Description

var description: String

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

var descriptionInStringsFileFormat: String

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

func description(withLocale: Any?)

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

func description(withLocale: Any?, indent: Int)

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

Initializers

init?(coder: NSCoder)
init(dictionary: NSDictionary)

Initializes a newly allocated dictionary and adds to it objects from another given dictionary.

init(dictionaryLiteral: (Any, Any)...)

Instance Properties

Instance Methods

func keyEnumerator()
func makeIterator()

Return an iterator over the elements of this sequence.

Subscripts