开发者

Enumerate NSDictionary with keys and objects, PHP style

开发者 https://www.devze.com 2023-01-17 01:35 出处:网络
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:

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:

for开发者_JAVA技巧each ($dictionary as $key => $value);


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/


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


Now much easier:

for (NSString * key in dict)
{
    id/* or your type */ value = dict[key];
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消