14

I'm using an NSSortDescriptor to sort NSDate objects in an ascending order. However, I need nil dates to be at the bottom of the list, whereas at the moment they come at the top.

Daniel Wood
  • 4,487
  • 3
  • 38
  • 36

3 Answers3

9

In the end I have decided that having nil values is not a good idea and if I want what were nil value to appear at the bottom of the ascending list I should set the dates to [NSDate distantFuture] and them check for this before displaying them. It turns out this makes more semantic sense in within the applications as well.

Daniel Wood
  • 4,487
  • 3
  • 38
  • 36
7

Looks like you already have a solution, but for anyone else looking to still use nil NSDates, and have them at the bottom, I use the following code where I sort descending, and then reverse the order of the objects sent to the compare.

_sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"dueDate"
                                                ascending:NO
                                               comparator:^NSComparisonResult(id obj1, id obj2)  {
                                                   return [obj2 compare:obj1];
                                               }];
Tim Ritchey
  • 171
  • 1
  • 9
6

Of course, I should use

initWithKey:ascending:selector:

and write my own comparison selector

Daniel Wood
  • 4,487
  • 3
  • 38
  • 36
  • Exactly. Do you custom logic to handle nil values and then call [myNSDateInstance compare:secondDate]; if second date is non nil. – Corey Floyd Jan 07 '10 at 17:40
  • That won't help, since `compare:` will be sent to the NSDate instances; if `nil` ends up the receiver, the result will be `NSOrderedSame`, and if the receiver is not `nil` but the argument is, I don't think any specific result is guaranteed. – Peter Hosey Jan 07 '10 at 18:07
  • This does not work when fetching from Core Data, unfortunately. – pkamb Aug 07 '15 at 23:44