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

// METHOD 1: This is the literal syntax was and it was added recently. Entries are added as key:value pairs
NSDictionary *daysOfTheWeek = @{
@"key1":@"Monday",
@"key2":@"Tuesday",
@"key3":@"Wednesday",
@"key4":@"Thursday",
@"key5":@"Friday",
@"key6":@"Saturday",
@"key7":@"Sunday"};

//METHOD 2: Create arrays of values and keys for the dictionary object.
NSArray *values = @[@"Avocado", @"Mango", @"Water Melon", @"Passion Fruit", @"Bread Fruit"];

NSArray *keys = @[@"avocado.png", @"mango.jpg", @"watermelon.png", @"passiongfruit.jpg", @"breadfruit.jpg"];

// Instantiate a dictionary object, using the values and keys arrays to initialize it
NSDictionary *dicFruits = [NSDictionary dictionaryWithObjects:values forKeys:keys];

// METHOD 3: Instantiate and initialize a dictionary object with (value, key) entries
NSDictionary *cleaningTasks = [NSDictionary dictionaryWithObjectsAndKeys:
@"Remove cobwebs", @"task1",
@"Clean and sanitized counter top", @"task2",
@"Dust picture frames", @"task3",
@"Appliances cleaned and shined",
@"task4", nil];

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 *cleaningTasks = [NSDictionary dictionaryWithObjectsAndKeys:
@"Remove cobwebs", @"task1",
@"Clean and sanitized counter top", @"task2",
@"Dust picture frames", @"task3",
@"Appliances cleaned and shined",
@"task4", nil];

// Display the dictionary's value for the third key
self.outputBox.text = [cleaningTasks objectForKey:@"task3"];
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 *daysOfTheWeek = @{@"key1":@"Monday",
@"key2":@"Tuesday",
@"key3":@"Wednesday",
@"key4":@"Thursday",
@"key5":@"Friday",
@"key6":@"Saturday",
@"key7":@"Sunday"};

// Place the dictionary's keys and values in array variables
NSString *dicKeys = [[daysOfTheWeek allKeys] componentsJoinedByString:@"\n"];
NSString *dicValues = [[daysOfTheWeek allValues] componentsJoinedByString:@"\n"];

// Display the dictionary's keys and values
self.outputBox.text = [dicKeys stringByAppendingFormat:@"\n\n%@",dicValues];
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
for (NSString *key in daysOfTheWeek) {
  // Display the dictionary's keys and values in the Debug window
  NSLog(@"%@ %@", key, [daysOfTheWeek valueForKey:key]);
}
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
// Instantiate a dictionary object, using the values and keys arrays to initialize it
NSArray *values = @[@"Avocado", @"Mango", @"Water Melon", @"Passion Fruit", @"Bread Fruit"];
NSArray *keys = @[@"avocado.png", @"mango.jpg", @"watermelon.png", @"passiongfruit.jpg", @"breadfruit.jpg"];
NSDictionary *dicFruits = [NSDictionary dictionaryWithObjects:values forKeys:keys];

// Sort the dictionary's keys and values in alphabetical order
NSArray *sortedDicKeys = [[dicFruits allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray *sortedDicValues = [[dicFruits allValues] sortedArrayUsingSelector:@selector(compare:)];

// Convert both arrays to string objects
NSString *stringKeys = [sortedDicKeys componentsJoinedByString:@"\n"];
NSString *stringValues = [sortedDicValues componentsJoinedByString:@"\n"];

// Display the sorted dictionary's keys and values in the UITextView control
self.outputBox.text = [stringKeys stringByAppendingFormat:@"\n\n%@",stringValues];
nsdictionary_fig4