Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an NSDictionary, descending. How do I send options with the `compare:options:` selector?

I am attempting to sort an NSDictionary.

From the Apple docs I see 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 have read that you can use compare:options:, and an NSStringCompareOptions to change the comparison to compare in the other direction.

However I don't understand how you send compare:options: with an option in the selector.

I want to do something like this:

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

How should I switch the order of the comparison?

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

like image 531
ck_ Avatar asked Apr 05 '13 03:04

ck_


2 Answers

Option 1: Use a comparator to invoke -compare: in reverse: (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 reverse the descending and ascending return statements and you should get just what you want.

Option 2: Reverse the array you have:

See How can I reverse a NSArray in Objective-C?

like image 66
paulmelnikow Avatar answered Nov 17 '22 16:11

paulmelnikow


I use :

    NSSortDescriptor *sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
    self. sortedKeys = [[self.keyedInventoryItems allKeys] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortOrder]];
like image 43
YvesLeBorg Avatar answered Nov 17 '22 15:11

YvesLeBorg