Sort an array of dictionaries by NSDate

I have a set of dictionaries. Inside each dictionary there is a key dateOfInfo (a NSDate ) and several other things. I want to sort an array for each dateOfInfo dictionary, the most recent of which is the first result.

How can i do this?

+4
source share
3 answers

You can sort using NSSortDescription , for example.

 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey: @"dateOfInfo" ascending: NO]; NSArray *sortedArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; [sortDescriptor release]; 

You can also use the method

 - (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context 
+16
source

The basic bubble sorting algorithm will work. In this case, you need to go through your array, use the valueKey value of the message in [array objectAtIndex:] to get the NSDate values. For a comparison of dates, see this post . So, if you are sorting in ascending order of date, just add an object with a lower date (remember matching sorting of bubbles?) To an array that will save your sorted result.

+1
source

try it,

  NSDateFormatter *fmtDate = [[NSDateFormatter alloc] init]; [fmtDate setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; NSComparator compareDates = ^(id string1, id string2) { NSDate *date1 = [fmtDate dateFromString:string1]; NSDate *date2 = [fmtDate dateFromString:string2]; return [date1 compare:date2]; }; NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"StartTime" ascending:YES comparator:compareDates]; [youArray sortUsingDescriptors:@[sortDesc1]]; 
0
source

All Articles