Is there a way to iterate over a dictionary?

HelloMoon picture HelloMoon · Aug 16, 2009 · Viewed 120.6k times · Source

I know NSDictionaries as something where you need a key in order to get a value. But how can I iterate over all keys and values in a NSDictionary, so that I know what keys there are, and what values there are? I know there is something called a for-in-loop in JavaScript. Is there something similar in Objective-C?

Answer

Adam Rosenfield picture Adam Rosenfield · Aug 16, 2009

Yes, NSDictionary supports fast enumeration. With Objective-C 2.0, you can do this:

// To print out all key-value pairs in the NSDictionary myDict
for(id key in myDict)
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an NSEnumerator:

NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);