The NSDictionary Class

An NSDictionary is nothing more than a collection of key-value pairs. The key-value pairs is referred to as an entry. An instance (object) of the NSDictionary class is immutable. This means once you’ve instantiated and initialize a dictionary object, you can’t add new entries or delete existing entries.

NSDictionary Syntax

[NSDictionary dictionaryWithObjectsAndKeys:value, key]
NSDictionary The object’s return type.
dictionaryWithObjectsAndKeys: This method is used to initialize the dictionary.
value This is where you provided the dictionary’s value.
key This is where you provide the dictionary’s key and it is used to access its value. The key must be a unique string. If you provide a key that is already used in the dictionary, the new entry associated with that key is discarded.
To practice source code presented in this lesson, you should download and unzip this file.
project_icon_codepractice
Launch the project (CodePractice.xcodeproj) and enter code in the viewController.m file’s buttonTapped method, then click the “Click Me” button to execute the method’s code.

Here are three methods of instantiating and initializing a dictionary object.

Common Methods of the NSDictionary Class

The NSDictionary class contain several methods for manipulating instances (objects) of its class. In this section I show you how to use a handful of them.

The objectForKey: method

This method is returns the value of dictionary entry based on the argument provided, which is the entry’s key. Code below demonstrates how how to display a single value of the cleaningTasks dictionary, in the UITextField control.

Code Output
nsdictionary_fig1
The allKeys and allValues Method

The allKeys method returns the dictionary’s keys, or an empty array if the dictionary has no entries. The allValues method returns the dictionary’s values, or an empty array if the dictionary has no entries. Code below demonstrates how to use both methods to display the daysOfTheWeek dictionary’s keys and values, in the UITextView control.

Code Output
nsdictionary_fig2

Another way you can display a dictionary’s keys and values is to use the NSLog() function in a for loop statement like this.

Code Output
nsdictionary_fig3

The keysSortedByValueUsingSelector: Method

This method sorts the dictionary’s keys or values in alphabetical order, then returns an array of the sorted dictionary keys or values. Code below demonstrates how to use the keysSortedByValueUsingSelector: method to sort keys and values of a dictionary, then display them in the UITextView control.

Code Output
nsdictionary_fig4