views:

4175

answers:

3

How do I use NSEnumerator with NSMutableDictionary, to print out all the keys and values?

Thanks!

+3  A: 

From the NSDictionary class reference:

You can enumerate the contents of a dictionary by key or by value using the NSEnumerator object returned by keyEnumerator and objectEnumerator respectively.

In other words:

NSEnumerator *enumerator = [myMutableDict keyEnumerator];
id aKey = nil;
while ( (aKey = [enumerator nextObject]) != nil) {
    id value = [myMutableDict objectForKey:anObject];
    NSLog(@"%@: %@", aKey, value);
}
BJ Homer
You can also enumerate the keys in the same order with fast enumeration in Objective-C 2.0 — just use for (NSString *key in myMutableDict) { ... } instead.
Quinn Taylor
+17  A: 

Unless you need to use NSEnumerator, you can use fast enumeration (which is faster) and concise.

for(NSString *aKey in myDictionary){

    NSLog(aKey);
    NSLog([[myDictionary valueForKey:aKey] string]); //made up method

}

Also you can use an Enumerator with fast enumeration:

NSEnumerator *enumerator = [myDictionary keyEnumerator];

 for(NSString *aKey in enumerator){

        NSLog(aKey);
        NSLog([[myDictionary valueForKey:aKey] string]); //made up method

    }

This is useful for things like doing the reverse enumerator in an array.

Corey Floyd
Don't forget you can also enumerate values only from a dictionary if you want: for (NSString *value in [myDictionary allValues]).
Kendall Helmstetter Gelner
True, but -allValues does create an intermediate (autoreleased) array, so be aware of the extra storage required.
Quinn Taylor
A: 

Hi,

I'm trying to find out what the keys are in an NSDicitionary I received from a foreign object. I'm trying to use an enumerator but just declaring it fails already:

NSDictionary* result = [self executeXMLRPCRequest:request byHandlingError:TRUE];   
NSEnumerator* enumerator = [result keyEnumerator];

results in

[NSCFBoolean keyEnumerator]: unrecognized selector sent to instance 0x...

What's wrong?

EDIT: OK, it turns out that result is returned as an id, but depending on the remote method I'm calling, it could be a boolean, a number or some sort of a collection, which I need to figure out at runtime!

Lex