The NSMutableDictionary Class

An NSMutableDictionary is nothing more than a collection of key-value pairs. A key-value pair is referred to as an entry. An instance (object) of the NSMutableDictionary class is mutable. This means once you’ve instantiated and initialize a dictionary object, you can add new entries or delete existing entries. The NSMutableDictionary class is a subclass of the NSDictionary object; therefore, you can use methods of the NSDictionary class to create and manipulate instances of the NSMutableDictionary class.
nsdictionary_inheritance
NSMutableDictionary Syntax

[NSMutableDictionary dictionaryWithObjectsAndKeys:value, key]
NSMutableDictionary 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 two methods of instantiating and initializing an NSMutableDictionary object.

Once you’ve instantiated and initialize an NSMutableDictionary object, you can display a single value in the UITextField control and all values in the UITextView control, using code shown below.

Code Output
nsmutabledictionary_fig1

Notice that the dictionary’s values aren’t in alphabetical order. Code below demonstrates how to use the NSDictionary’s keysSortedByValueUsingSelector: method to sort the NSMutableDictionary’s values in alphabetical order, then display them in the UITextView control.

Code Output
nsmutabledictionary_fig2

Common Methods of the NSMutableDictionary Class

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

The setObject: Method

This method add a new entry in the mutable dictionary. Code below shows how to use it.

Code Output
nsmutabledictionary_fig3

The removeAllObjects Method

This method does exactly what it say, remove all objects from a mutable dictionary. Code below shows how to use it.

Code Output
nsmutabledictionary_fig4