Next: Property Lists Up: NSDictionary Previous: Enumerating all the Keys

NSMutableDictionary

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];
AUTORELEASE (dict);
[dict setObject: @"/opt/picture.png"        
         forKey: @"Luca"]; 
[dict setObject: @"/home/nico/birthday.png" 
         forKey: @"Birthday Photo"];
[dict setObject: @"/home/nico/birthday.png" 
         forKey: @"Birthday Image"];
[dict setObject: @"/home/marghe/pic.jpg"    
         forKey: @"My Sister"];

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

[dict removeObjectforKey: @"Luca"];
this will remove the key @"Luca" and its associated value from the mutable dictionary.



Nicola 2002-01-13