Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSArray of NSDictionaries by string date in key?

I have been struggling to find an easy way to sort an NSMutableArray that contains NSDictionaries. Each NSDictionary has a key named "Date" which contains an NSString of a date (ex: 10/15/2014).

What I am looking to do is sort the array based on those strings in ascending order.

I have tried this with no luck:

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yy"];

    NSDate *d1 = [formatter dateFromString:s1];
    NSDate *d2 = [formatter dateFromString:s2];

    return [d1 compare:d2]; // ascending order
    return [d2 compare:d1]; // descending order
}

I have also tried this with no luck:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest"  ascending:YES];
    stories=[stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
    recent = [stories copy];

Each way results in a crash and I think it is because it is a NSString instead of a NSDate but I am just at a loss on how to do this.

Can anyone show me the correct way to accomplish this?

This is how I call the first block of code:

theDictionaries = [[theDictionaries sortedArrayUsingFunction:dateSort context:nil] mutableCopy];
like image 269
user3251233 Avatar asked Jan 30 '14 00:01

user3251233


1 Answers

You need to get the strings inside your dictionaries. It looks like you're trying to compare the dictionaries themselves. If you had an array called data, you would do something like this,

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy"];

self.data = [self.data sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    NSDate *d1 = [formatter dateFromString:obj1[@"date"]];
    NSDate *d2 = [formatter dateFromString:obj2[@"date"]];

    return [d1 compare:d2]; // ascending order
    return [d2 compare:d1]; // descending order
}];

NSLog(@"%@",self.data);
like image 163
rdelmar Avatar answered Sep 27 '22 21:09

rdelmar