for each loop in Objective-C for accessing NSMutable dictionary

Sagar R. Kothari picture Sagar R. Kothari · Jan 27, 2010 · Viewed 251.2k times · Source

I am finding some difficulty in accessing mutable dictionary keys and values in Objective-C.

Suppose I have this:

NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init];

I can set keys and values. Now, I just want to access each key and value, but I don't know the number of keys set.

In PHP it is very easy, something as follows:

foreach ($xyz as $key => $value)

How is it possible in Objective-C?

Answer

zneak picture zneak · Jan 27, 2010
for (NSString* key in xyz) {
    id value = xyz[key];
    // do stuff
}

This works for every class that conforms to the NSFastEnumeration protocol (available on 10.5+ and iOS), though NSDictionary is one of the few collections which lets you enumerate keys instead of values. I suggest you read about fast enumeration in the Collections Programming Topic.

Oh, I should add however that you should NEVER modify a collection while enumerating through it.