问题描述
我知道 NSDictionaries
需要一个 key
才能获得 value
.但是如何遍历 NSDictionary
中的所有 keys
和 values
,以便我知道有哪些键以及有哪些值?我知道在 JavaScript
中有一种叫做 for-in-loop 的东西.Objective-C
中是否有类似的东西?
I know NSDictionaries
as something where you need a key
in order to get a value
. But how can I iterate over all keys
and values
in a NSDictionary
, so that I know what keys there are, and what values there are? I know there is something called a for-in-loop in JavaScript
. Is there something similar in Objective-C
?
推荐答案
是的,NSDictionary
支持快速枚举.使用 Objective-C 2.0,您可以这样做:
Yes, NSDictionary
supports fast enumeration. With Objective-C 2.0, you can do this:
// To print out all key-value pairs in the NSDictionary myDict
for(id key in myDict)
NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
替代方法(如果您的目标是 Mac OS X 10.5 之前的版本,则必须使用该方法,但您仍然可以在 10.5 和 iPhone 上使用)是使用 NSEnumerator
:
The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an NSEnumerator
:
NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
这篇关于有没有办法遍历字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!