Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSDate objects in NSMutableArray using NSSortDescriptor?

In my project, I'm getting some data from an APi and I retreive the data into a NSMutableArray by parsing the JSON. It has a key called "StartDate" which is of the format : " mm/dd/yyyy hh:mm:ss " as shown below

StartDate: "5/18/2013 12:00:00 AM"

I'm saving these data to a resultArray .There are also 4 more keys for an object as my JSON is of the form

{
    EventId: "xxxx",
    Title: "xxx",
    Location: "xxxx",
    StartDate: "5/18/2013 12:00:00 AM",
    Link: null
}

there are multiple such objects here. All that I need to do is to sort the contents of the resultArray based on date(either ascending or descending), I use the following code

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"StartDate" ascending:TRUE];
[resultArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

But I;m getting a shuffled result, the sorting is not correct throughout, can anyone tel me where I had gone wrong .

Thanks

like image 325
DD_ Avatar asked Jan 15 '23 12:01

DD_


1 Answers

Should work

[resultArray sortUsingComparator:^NSComparisonResult(id a, id b) {

    static NSDateFormatter *dateFormatter = nil;

    if (!dateFormatter) {
        dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"mm/dd/yyyy hh:mm:ss"; 
    }

    NSString *date1String = [a valueForKey:@"StartDate"];
    NSString *date2String = [b valueForKey:@"StartDate"];

    NSDate *date1 = [dateFormatter dateFromString:date1String];
    NSDate *date2 = [dateFormatter dateFromString:date2String];

    return [date1 compare:date2];
}];
like image 152
AntonPalich Avatar answered Jan 21 '23 12:01

AntonPalich