Next: 3.5 NSMutableDictionary Up: 3 NSDictionary Previous: 3.3 Retrieving a value

3.4 Enumerating all the Keys and Values

Sometime, you need to iterate over all the key/value pairs in a dictionary. To do this, you use the method -allKeys to retrieve an array of all the keys in the dictionary; this array contains all the keys, in no particular (ie random) order. You can then cycle over this array, and for each key retrieve its value. The following example prints out all the key-values in a dictionary:
void
describeDictionary (NSDictionary *dict)
{ 
  NSArray *keys;
  int i, count;
  id key, value;

  keys = [dict allKeys];
  count = [keys count];
  for (i = 0; i < count; i++)
  {
    key = [keys objectAtIndex: i];
    value = [dict objectForKey: key];
    NSLog (@"Key: %@ for value: %@", key, value);
  }
}
As usual, this code is just an example of how to enumerate all the entries in a dictionary; in real life, to get a description of a NSDictionary, you just do NSLog (@"%@", myDictionary);.



2008-01-16