创建一个类别NSDate
,返回当前日历和时区从一天开始以来的时间间隔,然后使用该时间间隔进行排序。
@interface NSDate (CBVAdditions)
- (NSTimeInterval)cbvTimeIntervalSinceStartOfDay;
@end
@implementation NSDate (CBVAdditions)
- (NSTimeInterval)cbvTimeIntervalSinceStartOfDay
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
NSDateComponents *dateComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self];
[dateComponents setCalendar:calendar];
[dateComponents setTimeZone:timeZone];
NSInteger hoursComponent = dateComponents.hour * 3600;
NSInteger minutesComponent = dateComponents.minute * 60;
double secondsComponent = dateComponents.second;
NSTimeInterval toReturn = hoursComponent + minutesComponent + secondsComponent;
return toReturn;
}
@end
然后,你可以用NSSortDescriptor
一个键@"dateProperty.cbvTimeIntervalSinceStartOfDay"
来做实际的排序。例如,我展示了Event
类和一些完成排序的代码。
@interface Event : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSDate *eventDate;
@end
@implementation Event
- (NSString *)description
{
NSString *desc = [NSString stringWithFormat:@"%@, name = %@, eventDate = %@",[super description], self.name, [self.eventDate descriptionWithLocale:[NSLocale currentLocale]]];
return desc;
}
@end
...
Event *e1 = [Event new];
e1.eventDate = [NSDate date];
e1.name = @"e1";
Event *e2 = [Event new];
e2.eventDate = [NSDate dateWithTimeIntervalSinceNow:(-1 * 22 * 3600)];
e2.name = @"e2";
Event *e3 = [Event new];
e3.eventDate = [NSDate dateWithTimeIntervalSinceNow:3600];
e3.name = @"e3";
NSArray *events = @[e1,e2,e3];
NSLog(@"Events = %@", events);
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"eventDate.cbvTimeIntervalSinceStartOfDay" ascending:YES];
NSArray *sortedEvents = [events sortedArrayUsingDescriptors:@[sortDescriptor]];
NSLog(@"Sorted Events = %@", sortedEvents);
执行此代码显示以下输出:
2013-01-15 15:50:54.221 DateSortingFun[67319:c07] Events = (
"<Event: 0x717b050>, name = e1, eventDate = Tuesday, January 15, 2013, 3:50:54 PM Mountain Standard Time",
"<Event: 0x717b620>, name = e2, eventDate = Monday, January 14, 2013, 5:50:54 PM Mountain Standard Time",
"<Event: 0x717b650>, name = e3, eventDate = Tuesday, January 15, 2013, 4:50:54 PM Mountain Standard Time" )
2013-01-15 15:50:54.222 DateSortingFun[67319:c07] Sorted Events = (
"<Event: 0x717b050>, name = e1, eventDate = Tuesday, January 15, 2013, 3:50:54 PM Mountain Standard Time",
"<Event: 0x717b650>, name = e3, eventDate = Tuesday, January 15, 2013, 4:50:54 PM Mountain Standard Time",
"<Event: 0x717b620>, name = e2, eventDate = Monday, January 14, 2013, 5:50:54 PM Mountain Standard Time" )