16

I know you can Enumerate the keys or values of NSMutableDictionary using NSEnumerator. Is it possible to do both together? I'm looking for something similar to the PHP foreach enumerator like:

foreach ($dictionary as $key => $value);
Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
typeoneerror
  • 55,990
  • 32
  • 132
  • 223
  • 1
    http://stackoverflow.com/questions/3701126/get-the-array-index-in-for-statement-in-objective-c/3701165#3701165 – RolandasR Sep 23 '10 at 05:22

3 Answers3

62

Perhaps look into NSDictionary's method:

enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))

If you're not familiar with blocks in C/Objective-C, this is a good tutorial: http://thirdcog.eu/pwcblocks/

Sam
  • 2,707
  • 20
  • 25
35
NSDictionary* d = [NSDictionary dictionaryWithObjectsAndKeys:@"obj1",@"key1",
                                                           @"obj2",@"key2",
                                                           @"obj3",@"key3",
                                                           @"obj4",@"key4",nil];

for (id key in [d allKeys]) {
    NSLog(@"%@ - %@",key,[d objectForKey:key]);
}

Outputs:

keytest[7880:a0f] key3 - obj3
keytest[7880:a0f] key1 - obj1
keytest[7880:a0f] key4 - obj4
keytest[7880:a0f] key2 - obj2
ACBurk
  • 4,418
  • 4
  • 34
  • 50
  • 6
    One thing: Using fast enumeration on an `NSDictionary` already iterates the keys, so the `[d allKeys]` is unnecessary. – Wevah Sep 23 '10 at 05:42
  • I think the blocks are nicer, but this is what I ended up doing since I can't use blocks in my iphone app. – typeoneerror Sep 23 '10 at 06:17
  • 1
    yeah, blocks are the future but sometimes we have to live in the past – ACBurk Sep 23 '10 at 16:51
9

Now much easier:

for (NSString * key in dict)
{
    id/* or your type */ value = dict[key];
    ...
}
Dmitry Isaev
  • 3,888
  • 2
  • 37
  • 49
  • This response doesn't answer the question. The OP was looking for a way to enumerate keys and values together. This approach only enumerates keys, and requires an additional lookup to obtain the value associated with each key. – Greg Brown Sep 05 '16 at 12:56