The NSMutableDictionary object is very useful item in the Cocoa toolbox. It allows you to store values which are indexed by key. It is similar to the NSDictionary object with the exception that items can be added and removed dynamically. So let’s jump right in and take a look at some sample code.
Creating an NSMutableDictionaryObject
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
Creating the object is rather simple. We simply use the alloc and init methods to create our object. There are many other init methods that may make more sense depending on your situation so definitely check out the documentation.
Adding Objects to an NSDictionary
[dictionary setObject:@"Entry1" forKey:@"1"]; [dictionary setObject:@"Entry2" forKey:@"2"]; [dictionary setObject:@"Entry3" forKey:@"3"];
As you can see, adding objects to the NSDictionary is very simple. We use the setObject:forKey: method to assign values to specific keys. In this case, we’ve assigned the string “Entry 1” to the key “1′, “Entry 2” to the key “2”, and “Entry 3” to the key “3”.
Reading an object from an NSDictionary
NSLog(@"%@", [dictionary objectForKey:@"1"]);
Here we use the objectForKey method to request the value of a specific key in the NSDictionary (in our case the key is “1”). We pass this with the NSLog method so we can verify the value we get from the NSMutableDictionary. In this case, we should see “Entry 1” output to the log window.
Removing an object from an NSDictionary
Finally, we come to removing objects from an NSDictionary.
We simply use the removeObjectForKey method to remove an object from the NSDictionary. In the case above, we’ve removed the object for the key “1”, which is “Entry 1”. If we attempt to output the value for the key we removed, we would simply see a null value.
One final note is to remember to release your NSMutableDictionary object since we created it by using the alloc method. It can be released like so:
As you can see, using the NSMutableDictionary object is really easy and can be a great tool to have mastered. Until next time, happy coding!