objective-c 通过索引访问 NSMutableDictionary 中的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1475716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing objects in NSMutableDictionary by index
提问by 4thSpace
To display key/values from an NSMutableDictionary sequentially (in a tableview), I need to access them by index. If access by index could give the key at that index, I could than get the value. Is there a way to do that or a different technique?
要按顺序显示 NSMutableDictionary 中的键/值(在 tableview 中),我需要通过索引访问它们。如果按索引访问可以给出该索引处的键,我就可以获得该值。有没有办法做到这一点或不同的技术?
回答by Benno
You can get an NSArray containing the keys of the object using the allKeys method. You can then look into that by index. Note that the order in which the keys appear in the array is unknown. Example:
您可以使用 allKeys 方法获取包含对象键的 NSArray。然后你可以通过索引查看它。请注意,键在数组中出现的顺序是未知的。例子:
NSMutableDictionary *dict;
/* Create the dictionary. */
NSArray *keys = [dict allKeys];
id aKey = [keys objectAtIndex:0];
id anObject = [dict objectForKey:aKey];
EDIT: Actually, if I understand what you're trying to do what you want is easily done using fast enumeration, for example:
编辑:实际上,如果我了解您想要做什么,则可以使用快速枚举轻松完成,例如:
NSMutableDictionary *dict;
/* Put stuff in dictionary. */
for (id key in dict) {
id anObject = [dict objectForKey:key];
/* Do something with anObject. */
}
EDIT: Fixed typo pointed out by Marco.
编辑:修复了 Marco 指出的错别字。
回答by newacct
you can get an array of all the keys with the allKeysmethod of the dictionary; and then you can access the array by index. however, a dictionary by itself does not have an inherent ordering, so the ordering of the keys you get before and after a change to the dictionary can be completely different
您可以使用allKeys字典的方法获取所有键的数组;然后你可以通过索引访问数组。但是,字典本身没有固有的排序,因此在更改字典之前和之后获得的键的排序可能完全不同

