Сортировка NSDate без учета времени суток - просто дата - PullRequest
2 голосов
/ 28 декабря 2011

У меня есть контроллер массива с ключами nextCheck (NSDate), lastName (NSString) и firstName (NSString). Я установил дескрипторы сортировки для массива. Как вы можете видеть ниже, я сортирую сначала nextCheck, затем lastName, затем firstName. Это кажется неработающим, потому что NSDate состоит не только из компонента даты, но и из компонента времени. Существует ли простой способ сортировки только по компоненту даты?

[_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]];

Ответы [ 2 ]

4 голосов
/ 28 декабря 2011

Самое простое решение: добавить метод с именем nextVisitDate, возвращающий значение nextVisit "усеченный" до полуночи, и вместо этого отсортировать по nextVisitDate.

[_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 голосов
/ 28 декабря 2011

То, что я сделал, было, когда я создавал даты, я использовал только компоненты даты даты:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) 
                                          fromDate:[NSDate date]];
NSDate *currentDate = [calendar dateFromComponents:comps];
...