web-dev-qa-db-ja.com

Objective-Cのキーに基づいてNSDictionaryをソートできますか?

キーに基づいてNSDictionaryをソートできますか?

44
suse

キーを並べ替えてから、それらを反復処理してNSMutableArrayを作成できます。

NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys)
    [sortedValues addObject: [dict objectForKey: key]];
114
Max Seelemann

objectsForKeys:notFoundMarker:を使用する方がはるかに簡単です

NSDictionary *yourDictionary;
NSArray *sortedKeys = [yourDictionary.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
// As we using same keys from dictionary, we can put any non-nil value for the notFoundMarker, because it will never used
NSArray *sortedValues = [yourDictionary objectsForKeys:sortedKeys notFoundMarker:@""];
3