2010-08-27 9 views

risposta

109

È possibile ordinare i tasti e creare uno NSMutableArray eseguendo il iter su di essi.

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

Ho usato la risposta nella mia risposta a http://stackoverflow.com/a/13406407/257533 –

+4

Quindi questa è una risposta corretta o no? ottenuto un sacco di voti, ma non accettare? –

+0

Questa è la risposta corretta. Purtroppo, il metodo più semplice (in iOS 7) di '[dictionary keysSortedByValueUsingSelector: @selector (compare :)]' non funziona. Per qualche ragione, mi dà risultati che sono quasi casuali in ordine. Mi chiedo se 'keysSortedByValueUsingSelector:' fa qualcosa dove si inserisce nell'array in base all'ultimo valore dell'array, che è un po 'inutile. – mikeho

-1

E 'molto più semplice da usare per objectsForKeys:notFoundMarker: che

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:@""]; 
Problemi correlati