Joon. P
Joon. P

Reputation: 2298

Objective-C Dictionary keys sorting in descending order

I have an unordered dictionary like this:

@{ @"20101R" : @"value1", 
   @"20102R" : @"value2", 
   @"20131R" : @"value3", 
   @"20111R" : @"value4", 
   @"20122R" : @"value5" }

Each key represents Year and either 1R or 2R.

For UITableView, I wish to put 'keys' as title and 'values' as subtitle like this:

from latest key value -> oldest key value

title : 20131R
subtitle : value3

title : 20122R
subtitle : value5

title : 20111R
subtitle : value4

title : 20102R
subtitle : value2

title : 20101R
subtitle : value1

Can you help me sort this number-like string in descending order? What is the simplest way to do this? Thank you in advance.

Upvotes: 0

Views: 1086

Answers (1)

Jbryson
Jbryson

Reputation: 2905

Pull out the keys with

NSArray *keysArray = [dictionary allKeys];

Then sort the array:

NSArray *sortedArray = [keysArray sortedArrayUsingComparator:^NSComparisonResult(NSString*  _Nonnull obj1, NSString*  _Nonnull obj2) {
    return obj1 < obj2;
}];

Upvotes: 2

Related Questions