I am running the following code to sort my array in the order of ending soonest (nearest expiry_date to [NSDate date] (now).
However, whenever I run the comparator, it has no affect, at all on the array, and all objects retain their current positions. Please can you tell me where I am going wrong?
[self.questions sortUsingComparator:^NSComparisonResult(NSDictionary * question1, NSDictionary *question2) {
NSDate* dateq1 = [NSDate dateWithTimeIntervalSinceNow:[[question1 objectForKey:@"expiry_date"] floatValue]];
NSDate * dateq2 = [NSDate dateWithTimeIntervalSinceNow:[[question2 objectForKey:@"expiry_date"] floatValue]];
NSComparisonResult result = [dateq1 compare:dateq2];
NSLog(@"%@", result == NSOrderedAscending ? @"ASC" : result == NSOrderedDescending ? @"DESC" : @"SAME");
return result;
}];
The NSLog() returns the following:
DESC
DESC
ASC
I have tried reversing the comparison to have dateq2 in the place of dateq1 and vice versa, but the array never changes, even though the returned values do.
It looks like it is working to me (judging by your output), but maybe this is more succinct and therefore less error prone?