问题
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]];
回答1:
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]];
回答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];
来源:https://stackoverflow.com/questions/8651733/sort-nsdate-without-respect-to-the-time-of-day-just-the-date