Search code examples
iosobjective-csortingnsdictionarynssortdescriptor

Sort NSArray of NSDictionary objects using NSSortDescriptor


I have an array of dictionaries that contain information about high scores. I am trying to figure out how to sort them by the different values in the dictionaries but cannot get it to work.

An example shown below attempts to sort by "Score":

NSDictionary *highScoreDictionary1 = @{@"Score" : @52, @"Duration" : @230 , @"Date" : [NSDate date]};
NSDictionary *highScoreDictionary2 =  @{@"Score" : @23, @"Duration" : @230 , @"Date" : [NSDate date]};
NSDictionary *highScoreDictionary3 = @{@"Score" : @35, @"Duration" : @230 , @"Date" : [NSDate date]};

NSArray *highScoresArray = @[highScoreDictionary1, highScoreDictionary2, highScoreDictionary3];

NSSortDescriptor *highScoreSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Score" ascending:YES];  // Sort by Score
NSArray *sortDescriptorArray = [NSArray arrayWithObject:highScoreSortDescriptor];

[highScoresArray sortedArrayUsingDescriptors:sortDescriptorArray];

The output I get from NSLog(@"sorted array of dictionaries: %@", highScoresArray); is:

sorted array of dictionaries: (
        {
        Date = "2014-09-01 19:38:00 +0000";
        Duration = 230;
        Score = 52;
    },
        {
        Date = "2014-09-01 19:38:00 +0000";
        Duration = 230;
        Score = 23;
    },
        {
        Date = "2014-09-01 19:38:00 +0000";
        Duration = 230;
        Score = 35;
    }
)

How do I remedy this? Am I missing something here because it seems that the dictionaries are not being sorted by score.


Solution

  • highScoresArray = [highScoresArray sortedArrayUsingDescriptors:sortDescriptorArray];