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.
Asked
Active
Viewed 4,396 times
3 Answers
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
-
does the compare not have undefined behaviour if obj1 is nil and obj2 is a date? – Mihai Timar Dec 16 '14 at 21:52
-
Note for anyone trying to use this in Core Data: comparators are not supported and will throw a runtime exception (maybe only if your Core Data is SQLite backed) – Carson Holzheimer Dec 08 '21 at 06:44
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
-