2009-09-25 72 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方法鍵的數組;然後你可以通過索引訪問數組。然而,字典本身並不具有固有的順序,所以對字典進行更改前後得到的鍵的順序可以完全不同