2011-11-14 16 views
11

私はNSMutableDictionaryに文字列キーがあり、すべてのキーには独自の配列があります。私はキーのアルファベット順の値で辞書を再ソートしたい。これどうやってするの?どのようにNSMutableDictionaryをキー値でソートできますか?

+0

私は、キー値とNSMutableDictionaryをソートされていないしていると私は再ソートするには、同じNSMutableDictionaryをキー値をアルファベット順にします。それはNSMutableDictionaryで可能ですか? –

答えて

19

辞書は定義によってソートされていません。

特定の順序でキーを反復処理するには、辞書のキーを含む配列を並べ替えることができます。

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

他にもいくつかの方法があります。 NSComparatorでソートします。見てくださいhere

8

使用この1

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

私はこのコードを使ってソートされた辞書を検索しましたが、まだソートされていない 'code NSMutableDictionary * dicProjectListSorted = [NSMutableDictionary dictionary]; NSArray * sortedKeys = [keys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare :)]; NSMutableArray * sortedValues = [[[NSMutableArray alloc] init] autorelease];idオブジェクト= [dicProjectList objectForKey:key]; [sortedValues addObject:object]; [dicProjectListSorted setObject:sortedValues forKey:key]; } –

+0

このコードからuキー値を短くしてキー値を取得するとあなたのデータが得られます – Ron

+0

sortedKeysはソートされていますが、ループ内で辞書(dicProjectListSorted)を再作成しようとするとソートされます?? –

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