Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array of Dictionaries by NSDate

I have an array of dictionaries. Within each dictionary, there is a a key dateOfInfo (an NSDate) and several other things. I want to sort the array by each dictionaries dateOfInfo with the most recent being the first result.

How can I do this?

like image 655
Baub Avatar asked Sep 21 '11 22:09

Baub


2 Answers

You can sort using NSSortDescription, e.g.

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
like image 162
PengOne Avatar answered Nov 14 '22 07:11

PengOne


The basic bubble sorting algorithm would work. In this case you need to loop through your array, use valueForKey message on [array objectAtIndex:] to get the NSDate values. For comparing dates see this post . So if you are sorting in ascending order of date, just add the object with the lower date (remember bubble sort comparisons?) to an array which will hold your sorted result.

like image 29
Bourne Avatar answered Nov 14 '22 06:11

Bourne