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
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];
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With