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" )