NSMutableDictionary simplicity

As you all know an NSDictionary object stores a mutable set of entries. An NSDictionary is immutable. If you need a dictionary which you can change, then you should use NSMutableDictionary. NSMutableDictionary is a subclass of NSDictionary, so that you can do with an NSMutableDictionary everything which you can do with a simple NSDictionary plus, you can modify it.

To set the value of a key in a dictionary, you can use -setObject:forKey:. If the key is not yet in the dictionary, it is added with the given value. If the key is already in the dictionary, its previous value is removed from the dictionary (which has the important side-effect that it is sent a -release message), and the new one is is put in its place (the new one receives a -retain message when it is added, as usual). You should note that, while values are retained, keys are instead copied.

So, if you use a NSMutableDictionary, you can create our usual dictionary as follows:

NSMutableDictionary *dict;

dict = [NSMutableDictionary new];

// or

dict = [[NSMutableDictionary alloc] init];

// To add a key and its associated value, you can just use the method -setObject:forKey:

[dict setObject: @”Mauro” forKey: @”1.User”];

[dict setObject: @”Radu” forKey: @”2.User”];

[dict setObject: @”Sergei” forKey:@”3.User”];

[dict setObject: @”Luke” forKey: @”4.User”];

// To remove a key and its associated value, you can just use the method -removeObjectForKey::

[dict removeObjectforKey: @”1.User”];

// this will remove the key @”1.User” and its associated value @”Mauro” from the mutable dictionary.

// If you want to permanent save all values in .xml file for given keys just make something like this:

NSString *path = [NSHomeDirectory() stringByAppendingString:[NSStringstringWithFormat:@”/Documents/Users.xml”]];

[dict writeToFile:path atomically:YES];

// If you want to load permanent saved values and key into new dictionary just do something like this:

NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];

// If you want add some new key value pairs into existing dictionary from some other dictionary just use this method below

[dict addEntriesFromDictionary:newDict];

Can not be simpler. More features – just check NSDictionary.h file in documentation. Cheers! :)