使用PHP样式的键和对象枚举NSDictionary

时间:2021-06-16 12:18:05

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:

我知道你可以使用NSEnumerator枚举NSMutableDictionary的键或值。有可能一起做两件事吗?我正在寻找类似于PHP foreach枚举器的东西,如:

foreach ($dictionary as $key => $value);

3 个解决方案

#1


57  

Perhaps look into NSDictionary's method:

也许看看NSDictionary的方法:

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/

如果您不熟悉C / Objective-C中的块,这是一个很好的教程:http://thirdcog.eu/pwcblocks/

#2


34  

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

#3


5  

Now much easier:

现在更容易:

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

#1


57  

Perhaps look into NSDictionary's method:

也许看看NSDictionary的方法:

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/

如果您不熟悉C / Objective-C中的块,这是一个很好的教程:http://thirdcog.eu/pwcblocks/

#2


34  

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

#3


5  

Now much easier:

现在更容易:

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