I know dictionaries as something where you need a key in order to get a value. But what would I do, when I need to iterate over all keys and values in that dictionary so that I know what keys are there, and what values are there? Is that possible to do? I know in JavaScript there's something called for-in-loop. But in objective-c / cocoa-touch?
+12
A:
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]);
Adam Rosenfield
2009-08-16 14:40:16