Sort NSDictionary, Descent. How to send parameters using the `compare: options:` selector option?

I am trying to sort an NSDictionary.

From the Apple Docs, I see that you can use keysSortedByValueUsingSelector :

 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:63], @"Mathematics", [NSNumber numberWithInt:72], @"English", [NSNumber numberWithInt:55], @"History", [NSNumber numberWithInt:49], @"Geography", nil]; NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:)]; 

which gives:

 // sortedKeysArray contains: Geography, History, Mathematics, English 

but I want:

 // sortedKeysArray contains: English, Mathematics, History, Geography 

I read that you can use compare:options: and NSStringCompareOptions to change the comparison to compare in the other direction.

However, I do not understand how you send compare:options: with an option to the selector.

I want to do something like this:

 NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:@selector(compare:options:NSOrderDescending)]; 

How to switch the comparison order?

Related: https://discussions.apple.com/thread/3411089?start=0&tstart=0

+7
source share
2 answers

Option 1: Use the comparator to call -compare: in reverse order: (Thanks Dan Shelly!)

 NSArray *blockSortedKeys = [dict keysSortedByValueUsingComparator: ^(id obj1, id obj2) { // Switching the order of the operands reverses the sort direction return [objc2 compare:obj1]; }]; 

Just cancel the downstream and upstream return statements, and you should get exactly what you want.

Option 2: The inverse array that you have:

See How can I undo NSArray in Objective-C?

+13
source

I use:

  NSSortDescriptor *sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]; self. sortedKeys = [[self.keyedInventoryItems allKeys] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortOrder]]; 
+4
source

All Articles