I am trying to sort my NSDictionary as suggested at Getting NSDictionary keys sorted by their respective values. Does the comparator block sort the keys in ascending or descending order of values in NSDictionary? I want to display the keys according to ascending order of values. In other words, is the sorting operation done by the comparator block is in ascending or descending order? Thank you.
Asked
Active
Viewed 779 times
0
-
1Note that you **cannot** sort the actual dictionary entries. Dictionary entries (as returned by a `for` loop on the dictionary) are in indeterminate order. – Hot Licks Mar 03 '15 at 02:35
2 Answers
2
The resulting array will be in ascending order, where ascending is determined by the behavior of the comparator. (I.e. it might be different than what a casual observer would expect.)
The comparator receives two objects, often called obj1
and obj2
. If it returns NSOrderedAscending
for a given pair of objects, then obj1
will be ordered before obj2
in the resulting array. If it returns NSOrderedDescending
then obj2
will be ordered before obj1
. If it returns NSOrderedSame
, then obj1
and obj2
will have arbitrary relative order in the resulting array.
By the way, a simple test program could have given you the answer.

Ken Thomases
- 88,520
- 7
- 116
- 154
2
In this code is in ascending order:
myArray = [myDict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
To descending order, switch:
return (NSComparisonResult)NSOrderedDescending;
and
return (NSComparisonResult)NSOrderedAscending;

Claudio Castro
- 1,541
- 12
- 28