简体   繁体   中英

Getting NSDictionary keys sorted by their respective values in Ascending order

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.

The resulting array will be in ascending order, where ascending is determined by the behavior of the comparator. (Ie 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM