Next: Enumerating all the Keys Up: NSDictionary Previous: Creating a NSDictionary

Retrieving a value with objectForKey:

To retrieve the value associated with a given key, you may use the method -objectForKey:, as in the following example:
NSDictionary *dict;
NSString *path;

dict = [NSDictionary dictionaryWithObjectsAndKeys:
               @"/opt/picture.png", @"Luca", 
               @"/home/nico/birthday.png", @"Birthday Photo", 
               @"/home/nico/birthday.png", @"Birthday Image", 
               @"/home/marghe/pic.jpg", @"My Sister", nil];

// Following will set path to /home/nico/birthday.png
path = [dict objectForKey: @"Birthday Image"];
If the key is not in the dictionary, -objectForKey: will return nil, for example
// Following will set path to nil
path = [dict objectForKey: @"My Mother"];
(assuming dict is the one created in the previous example). In real life applications, in most cases you don't know if the key is in the dictionary or not until you try retrieving the value associated with it. In these cases, you need to check the result of objectForKey: to make sure it's not nil before using it. For example, assuming that dict is a dictionary, you would normally do -
NSString *imageName = @"My Father";
NSString *path;

path = [dict objectForKey: imageName];

if (path == nil)
  {
    // This means the dictionary does not contain it
    NSLog (@"Don't know the path to the image '%@'", imageName);
  }
else
  {
    // Do something with path
  }
This is also the standard way to check that a key is contained in a dictionary - you call objectForKey: and compare the result with nil.



Nicola 2002-01-13