<!--
{
  "availability" : [
    "iOS: 2.0.0 -",
    "iPadOS: 2.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.0.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSDictionary",
  "metadataVersion" : "0.1.0",
  "role" : "Class",
  "symbol" : {
    "kind" : "Class",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSDictionary"
  },
  "title" : "NSDictionary"
}
-->

# NSDictionary

A static collection of objects associated with unique keys.

```
class NSDictionary
```

## Overview

You can use this type in Swift instead of a <doc://com.apple.documentation/documentation/Swift/Dictionary> in cases that require reference semantics.

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`](/documentation/Foundation/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 <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/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](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/BasicPrinciples.html#//apple_ref/doc/uid/20002170)). Neither a key nor a value can be `nil`; if you need to represent a null value in a dictionary, you should use [`NSNull`](/documentation/Foundation/NSNull).

`NSDictionary` is “toll-free bridged” with its Core Foundation counterpart, <doc://com.apple.documentation/documentation/CoreFoundation/CFDictionary>. See [Toll-Free Bridging](https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/Toll-FreeBridgin/Toll-FreeBridgin.html#//apple_ref/doc/uid/TP40010810-CH2) for more information on toll-free bridging.

### Creating NSDictionary Objects Using Dictionary Literals

In addition to the provided initializers, such as [`init(objects:forKeys:)`](/documentation/Foundation/NSDictionary/init(objects:forKeys:)), you can create an `NSDictionary` object using a *dictionary literal*.

```swift
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:`](/documentation/Foundation/NSDictionary/dictionaryWithObjects:forKeys:count:) method.

```objc
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:`](/documentation/Foundation/NSDictionary/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](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html#//apple_ref/doc/uid/TP40011210-CH4) in [Programming with Objective-C](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011210).

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](https://developer.apple.com/library/archive/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID390) in [The Swift Programming Language (Swift 4.1)](https://developer.apple.com/library/archive/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097).

### Accessing Values Using Subscripting

In addition to the provided instance methods, such as [`object(forKey:)`](/documentation/Foundation/NSDictionary/object(forKey:)), you can access `NSDictionary` values by their keys using *subscripting*.

```swift
let value = dictionary["helloString"]
```

### Enumerating Entries Using for-in Loops

In addition to the provided instance methods, such as [`enumerateKeysAndObjects(_:)`](/documentation/Foundation/NSDictionary/enumerateKeysAndObjects(_:)), you can enumerate `NSDictionary` entries using *for-in loops*.

```swift
for (key, value) in dictionary {
    print("Value: \(value) for key: \(key)")
}
```

In Objective-C, `NSDictionary` conforms to the [`NSFastEnumeration`](/documentation/Foundation/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](https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/ClassCluster.html#//apple_ref/doc/uid/TP40008195-CH7). Any subclass must override the following primitive methods:

- [`init(objects:forKeys:count:)`](/documentation/Foundation/NSDictionary/init(objects:forKeys:count:))
- [`count`](/documentation/Foundation/NSDictionary/count)
- [`object(forKey:)`](/documentation/Foundation/NSDictionary/object(forKey:))
- [`keyEnumerator()`](/documentation/Foundation/NSDictionary/keyEnumerator())

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`](/documentation/Foundation/NSMapTable) and the corresponding Core Foundation type, <doc://com.apple.documentation/documentation/CoreFoundation/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`](/documentation/Foundation/NSDictionary/dictionary)

Creates an empty dictionary.

[`init()`](/documentation/Foundation/NSDictionary/init())

Initializes a newly allocated dictionary.

### Creating a Dictionary from Objects and Keys

[`dictionaryWithObjects:forKeys:`](/documentation/Foundation/NSDictionary/dictionaryWithObjects:forKeys:)

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

[`dictionaryWithObjects:forKeys:count:`](/documentation/Foundation/NSDictionary/dictionaryWithObjects:forKeys:count:)

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

[`init(objects:forKeys:)`](/documentation/Foundation/NSDictionary/init(objects:forKeys:))

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

[`init(objects:forKeys:count:)`](/documentation/Foundation/NSDictionary/init(objects: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:`](/documentation/Foundation/NSDictionary/dictionaryWithObjectsAndKeys:)

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

[`initWithObjectsAndKeys:`](/documentation/Foundation/NSDictionary/initWithObjectsAndKeys:)

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

[`init(object:forKey:)`](/documentation/Foundation/NSDictionary/init(object:forKey:))

Creates a dictionary containing a given key and value.

### Creating a Dictionary from Another Dictionary

[`dictionaryWithDictionary:`](/documentation/Foundation/NSDictionary/dictionaryWithDictionary:)

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

[`init(dictionary:)`](/documentation/Foundation/NSDictionary/init(dictionary:)-9fw1u)

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

[`init(dictionary:copyItems:)`](/documentation/Foundation/NSDictionary/init(dictionary:copyItems:))

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

[`init(dictionaryLiteral:)`](/documentation/Foundation/NSDictionary/init(dictionaryLiteral:))

Initializes a newly allocated dictionary from the given key-value pairs.

### Creating a Dictionary from an External Source

[`dictionaryWithContentsOfURL:error:`](/documentation/Foundation/NSDictionary/dictionaryWithContentsOfURL:error:)

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

[`init(contentsOfURL:error:)`](/documentation/Foundation/NSDictionary/init(contentsOfURL:error:))

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

[`dictionaryWithContentsOfFile:`](/documentation/Foundation/NSDictionary/dictionaryWithContentsOfFile:)

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

[`init(contentsOfFile:)`](/documentation/Foundation/NSDictionary/init(contentsOfFile:))

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

### Creating a Dictionary from an NSCoder

[`init(coder:)`](/documentation/Foundation/NSDictionary/init(coder:))

Creates a dictionary initialized from data in the provided unarchiver.

### Creating Key Sets for Shared-Key Optimized Dictionaries

[`sharedKeySet(forKeys:)`](/documentation/Foundation/NSDictionary/sharedKeySet(forKeys:))

Creates a shared key set object for the specified keys.

### Counting Entries

[`count`](/documentation/Foundation/NSDictionary/count)

The number of entries in the dictionary.

### Comparing Dictionaries

[`isEqual(to:)`](/documentation/Foundation/NSDictionary/isEqual(to:))

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`](/documentation/Foundation/NSDictionary/allKeys)

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

[`allKeys(for:)`](/documentation/Foundation/NSDictionary/allKeys(for:))

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

[`allValues`](/documentation/Foundation/NSDictionary/allValues)

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

[`value(forKey:)`](/documentation/Foundation/NSDictionary/value(forKey:))

Returns the value associated with a given key.

[`getObjects:andKeys:count:`](/documentation/Foundation/NSDictionary/getObjects:andKeys:count:)

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

[`getObjects:andKeys:`](/documentation/Foundation/NSDictionary/getObjects:andKeys:)

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

[`objects(forKeys:notFoundMarker:)`](/documentation/Foundation/NSDictionary/objects(forKeys:notFoundMarker:))

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

[`object(forKey:)`](/documentation/Foundation/NSDictionary/object(forKey:))

Returns the value associated with a given key.

[`subscript(_:)`](/documentation/Foundation/NSDictionary/subscript(_:)-52n56)

Returns the value associated with a given key.

[`subscript(_:)`](/documentation/Foundation/NSDictionary/subscript(_:)-1bt1b)

Accesses the value associated with a given key.

### Enumerating Dictionaries

[`keyEnumerator()`](/documentation/Foundation/NSDictionary/keyEnumerator())

Provides an enumerator to access the keys in the dictionary.

[`objectEnumerator()`](/documentation/Foundation/NSDictionary/objectEnumerator())

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

[`enumerateKeysAndObjects(_:)`](/documentation/Foundation/NSDictionary/enumerateKeysAndObjects(_:))

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

[`enumerateKeysAndObjects(options:using:)`](/documentation/Foundation/NSDictionary/enumerateKeysAndObjects(options:using:))

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

[`makeIterator()`](/documentation/Foundation/NSDictionary/makeIterator())

Returns an iterator over the elements of this sequence.

[`countByEnumeratingWithState:objects:count:`](/documentation/Foundation/NSDictionary/countByEnumeratingWithState:objects:count:)

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

### Sorting Dictionaries

[`keysSortedByValue(using:)`](/documentation/Foundation/NSDictionary/keysSortedByValue(using:))

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

[`keysSortedByValue(comparator:)`](/documentation/Foundation/NSDictionary/keysSortedByValue(comparator:))

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.

[`keysSortedByValue(options:usingComparator:)`](/documentation/Foundation/NSDictionary/keysSortedByValue(options: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

[`keysOfEntries(passingTest:)`](/documentation/Foundation/NSDictionary/keysOfEntries(passingTest:))

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

[`keysOfEntries(options:passingTest:)`](/documentation/Foundation/NSDictionary/keysOfEntries(options:passingTest:))

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

### Storing Dictionaries

[`write(to:)`](/documentation/Foundation/NSDictionary/write(to:))

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

[`write(to:atomically:)`](/documentation/Foundation/NSDictionary/write(to:atomically:))

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

[`write(toFile:atomically:)`](/documentation/Foundation/NSDictionary/write(toFile:atomically:))

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

### Accessing File Attributes

These convenience methods are for use with dictionaries returned by the [`FileManager`](/documentation/Foundation/FileManager)

A convenient interface to the contents of the file system, and the primary means of interacting with it. method [`attributesOfItem(atPath:)`](/documentation/Foundation/FileManager/attributesOfItem(atPath:))

Returns the attributes of the item at a given path., and allow you to access POSIX and HFS attributes for files and directories.

[`fileSize()`](/documentation/Foundation/NSDictionary/fileSize())

Returns the file’s size, in bytes.

[`fileType()`](/documentation/Foundation/NSDictionary/fileType())

Returns the file type.

[`fileCreationDate()`](/documentation/Foundation/NSDictionary/fileCreationDate())

Returns the file’s creation date.

[`fileModificationDate()`](/documentation/Foundation/NSDictionary/fileModificationDate())

Returns file’s modification date.

[`filePosixPermissions()`](/documentation/Foundation/NSDictionary/filePosixPermissions())

Returns the file’s POSIX permissions.

[`fileOwnerAccountID()`](/documentation/Foundation/NSDictionary/fileOwnerAccountID())

Returns the file’s owner account ID.

[`fileOwnerAccountName()`](/documentation/Foundation/NSDictionary/fileOwnerAccountName())

Returns the file’s owner account name.

[`fileGroupOwnerAccountID()`](/documentation/Foundation/NSDictionary/fileGroupOwnerAccountID())

Returns file’s group owner account ID.

[`fileGroupOwnerAccountName()`](/documentation/Foundation/NSDictionary/fileGroupOwnerAccountName())

Returns the file’s group owner account name.

[`fileExtensionHidden()`](/documentation/Foundation/NSDictionary/fileExtensionHidden())

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

[`fileIsImmutable()`](/documentation/Foundation/NSDictionary/fileIsImmutable())

Returns a Boolean value indicating whether the file is immutable.

[`fileIsAppendOnly()`](/documentation/Foundation/NSDictionary/fileIsAppendOnly())

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

[`fileSystemFileNumber()`](/documentation/Foundation/NSDictionary/fileSystemFileNumber())

Returns the filesystem file number.

[`fileSystemNumber()`](/documentation/Foundation/NSDictionary/fileSystemNumber())

Returns the filesystem number.

[`fileHFSTypeCode()`](/documentation/Foundation/NSDictionary/fileHFSTypeCode())

Returns file’s HFS type code.

[`fileHFSCreatorCode()`](/documentation/Foundation/NSDictionary/fileHFSCreatorCode())

Returns the file’s HFS creator code.

### Describing a Dictionary

[`description`](/documentation/Foundation/NSDictionary/description)

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

[`descriptionInStringsFileFormat`](/documentation/Foundation/NSDictionary/descriptionInStringsFileFormat)

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

[`description(withLocale:)`](/documentation/Foundation/NSDictionary/description(withLocale:))

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

[`description(withLocale:indent:)`](/documentation/Foundation/NSDictionary/description(withLocale:indent:))

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

### Supporting Types

[`NSDictionary.Iterator`](/documentation/Foundation/NSDictionary/Iterator)

A class that you use to provide members of a dictionary, one-by-one.



---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)