2

I have an array controller with keys of nextCheck (NSDate), lastName (NSString), and firstName (NSString). I have set the sort descriptors for the array. As you can see below, I am sorting by nextCheck first, then lastName, then firstName. This appears to not be working because the NSDate is made up of not only a date component but also a time component. Is there an easy way to sort by the date component only?

[_arrayCurrentVisits setSortDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"nextVisit" ascending:YES selector:@selector(compare:)],[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)], [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)], nil]];
docwelch
  • 75
  • 6

2 Answers2

4

The simplest solution would be to add a method called nextVisitDate returning the value of nextVisit "truncated" to midnight, and sort on nextVisitDate instead.

[_arrayCurrentVisits setSortDescriptors:[ //                           vvv HERE vvv
    NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"nextVisitDate"  ascending:YES selector:@selector(compare:)]
,   [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]
,   [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]
,   nil]];
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

What I did, was when I created dates I only used the date components of the date:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) 
                                          fromDate:[NSDate date]];
NSDate *currentDate = [calendar dateFromComponents:comps];
agilityvision
  • 7,901
  • 2
  • 29
  • 28