2009-09-25 71 views
52

要按顺序显示NSMutableDictionary中的键/值(在tableview中),我需要通过索引访问它们。如果通过索引访问可以在该索引处给出关键字,那么我可以获得该值。有没有办法做到这一点或不同的技术?按索引访问NSMutableDictionary中的对象

+0

什么时候做:NSMutableDictionary * tmpDict = [[NSMutableDictionary alloc] init]; [tmpDict setObject:@“CN-GSM”forKey:@“Provider:”]; [tmpDict setObject:@“10010”forKey:@“Number:”]; [tmpDict setObject:@“Yes”forKey:@“Free:”]; NSLog(@“%@”,[tmpdict allKeys]); [tmpDict发布];为什么输出不按我添加到tmpDict的值排序? – ZYiOS 2010-12-02 05:46:28

回答

119

您可以使用包含对象的键的NSArray allKeys方法。然后你可以通过索引来查看。请注意,键在数组中显示的顺序未知。例如:

NSMutableDictionary *dict; 

/* Create the dictionary. */ 

NSArray *keys = [dict allKeys]; 
id aKey = [keys objectAtIndex:0]; 
id anObject = [dict objectForKey:aKey]; 

编辑:其实,如果我理解你想你想很容易利用快速列举完成,例如什么什么:

NSMutableDictionary *dict; 

/* Put stuff in dictionary. */ 

for (id key in dict) { 
    id anObject = [dict objectForKey:key]; 
    /* Do something with anObject. */ 
} 

编辑:固定错字所指出的马可。

+2

“allkeys”是“allKeys” – Mark 2011-04-09 22:25:19

+0

在tableview中的'cellForRowAtIndexPath'中可能是:'NSArray * keys = [colors allKeys]; NSString * key = [keys objectAtIndex:indexPath.row]; cell = [tv dequeueReusableCellWithIdentifier:@“CellColour”forIndexPath:indexPath]; cell.textLabel.text = [colors objectForKey:key]; cell.backgroundColor = [self colorFromHexString:key];' – 2013-11-08 14:23:33

9

你可以得到所有字典的allKeys方法键的数组;然后你可以通过索引访问数组。然而,字典本身并不具有固有的顺序,所以对字典进行更改前后得到的键的顺序可以完全不同