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.
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. |
Here are two methods of instantiating and initializing an NSMutableDictionary object.
// METHOD 1: This is the literal syntax was and it was added recently. Entries are added as key:value pairs NSMutableDictionary *daysOfTheWeek = @{ @"key1":@"Monday", @"key2":@"Tuesday", @"key3":@"Wednesday", @"key4":@"Thursday", @"key5":@"Friday", @"key6":@"Saturday", @"key7":@"Sunday"}; // METHOD 2: Instantiate and initialize a dictionary object. Entries are added as value, key NSMutableDictionary *cleaningTasks = [NSMutableDictionary dictionaryWithObjectsAndKeys: @"Remove cobwebs", @"task1", @"Clean and sanitized counter top", @"task2", @"Dust picture frames", @"task3", @"Appliances cleaned and shined", @"task4", nil];
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.
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.
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.
The removeAllObjects Method
This method does exactly what it say, remove all objects from a mutable dictionary. Code below shows how to use it.