2011-11-14 36 views
11

我有一個NSMutableDictionary與字符串鍵,每個鍵都有自己的數組。我想按字母順序重新排序字典中的鍵值。我怎樣才能做到這一點?我如何使用鍵值對NSMutableDictionary進行排序?

+0

我已經不排序的NSMutableDictionary與鍵值,我想重新排序相同的NSMutableDictionary與鍵值按字母順序。這可能與NSMutableDictionary? –

回答

19

字典根據定義未排序。

要按特定順序遍歷鍵,可以對包含字典鍵的數組進行排序。

NSArray *keys = [theDictionary allKeys]; 
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compareMethod:)]; 

還有其他幾種sorted...方法,例如,用NSComparator排序。看看here

8

使用這一個

NSArray *myKeys = [Dict allKeys]; 
NSArray *sortedKeys = [myKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 
NSMutableArray *sortedValues = [[[NSMutableArray alloc] init] autorelease]; 

for(id key in sortedKeys) { 
    id object = [Dict objectForKey:key]; 
    [sortedValues addObject:object]; 
} 
+0

我用這個代碼檢索排序的字典,但仍然得到它未排序'代碼NSMutableDictionary * dicProjectListSorted = [NSMutableDictionary詞典]; NSArray * sortedKeys = [keys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare :)]; NSMutableArray * sortedValues = [[[[NSMutableArray alloc] init] autorelease]; for(id key in sortedKeys){ id object = [dicProjectList objectForKey:key]; [sortedValues addObject:object]; [dicProjectListSorted setObject:sortedValues forKey:key]; } –

+0

從這個代碼你得到的短鍵值和thn的關鍵值你得到你的數據 – Ron

+0

sortedKeys得到正確的排序,但當我嘗試重新創建字典(dicProjectListSorted)在循環內我得到它未排序? –

2
NSDictionary *yourDictionary; 
NSArray *sortedKeys = [yourDictionary.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]]; 
NSArray *sortedValues = [yourDictionary objectsForKeys:sortedKeys notFoundMarker:@""]; 
相關問題