Question

I have an array of dictionaries. These dictionaries have a format like this:

NSDictionary *oneDict = @{
              @"code": @"123"
              @"name": @"car"
              @"date": creationDate
}

these dictionaries are stored in a NSArray.

I need to extract the dictionary with the most recent date from that array.

I can discover the most recent date by doing this:

NSArray *extractDates = [array objectForKey:@"date"];
NSArray sortedDates = [extractDates sortedArrayUsingSelector:@selector(compare:)];
NSDate *mostRecentDate = (NSDate *)[sortedDates lastObject];

Now I know, I can interact over the array and look for that date, so I can get the dictionary, but I wonder if Objective-C has some sort of mechanism that can do that directly.

Was it helpful?

Solution

Try this,

NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                     sortDescriptorWithKey:@"date" 
                                                 ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedArray = [array
         sortedArrayUsingDescriptors:sortDescriptors];

NSDictionary *dict = (NSDictionary *)[sortedArray lastObject];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top