Xcode 对NSDate进行排序,不考虑一天中的时间,只考虑日期
我有一个数组控制器,其键为nextCheck(NSDate)、lastName(NSString)和firstName(NSString)。我已经为数组设置了排序描述符。正如你们在下面看到的,我先按nextCheck排序,然后按lastName排序,然后按firstName排序。这似乎不起作用,因为NSDate不仅由日期组件组成,而且还由时间组件组成。是否有一种仅按日期组件排序的简单方法Xcode 对NSDate进行排序,不考虑一天中的时间,只考虑日期,xcode,nsdate,nssortdescriptor,Xcode,Nsdate,Nssortdescriptor,我有一个数组控制器,其键为nextCheck(NSDate)、lastName(NSString)和firstName(NSString)。我已经为数组设置了排序描述符。正如你们在下面看到的,我先按nextCheck排序,然后按lastName排序,然后按firstName排序。这似乎不起作用,因为NSDate不仅由日期组件组成,而且还由时间组件组成。是否有一种仅按日期组件排序的简单方法 [_arrayCurrentVisits setSortDescriptors:[NSArray array
[_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]];
我所做的是,当我创建日期时,我只使用日期的日期组件:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit)
fromDate:[NSDate date]];
NSDate *currentDate = [calendar dateFromComponents:comps];
最简单的解决方案是将
nextVisit
的值“截断”到午夜,然后在nextVisit
上排序
[_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]];
谢谢这两个答案。我会用其中一个。