NextDateMatchingDay Objective-C メソッド - このコードよりも良い方法はありますか?
- (NSDate*)NextDateMatchingDay:(NSDateComponents*)dayTime {
// Find next date (including date & time) from current date, for which:
// (a) the DayOfWeek(no time) matches that dayOfWeek from the input "dateTime" NSDateComponents
// (b) the date is > currentDateTime
// (c) the final date time will be based on the time passed in by "dateTime" NSDateComponents
// e.g. dayTime=Sun10am's, currentDate=Sun1st2pm => result=Sun8th10am
// e.g. dayTime=Sun10am's, currentDate=Sun1st9am => result=Sun1st10am
// e.g. dayTime=Sun10am's, currentDate=Fri1st1pm => result=Sun8th10am
// Prepare
NSDate *currDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *addComps = [[[NSDateComponents alloc] init] autorelease];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* currComps = [gregorian components:unitFlags fromDate:currDate];
NSInteger daysCounter = 0;
do {
[addComps setDay:daysCounter];
NSDate *futureDate = [gregorian dateByAddingComponents:addComps toDate:currDate options:0];
NSDateComponents* futureComps = [gregorian components:unitFlags fromDate:futureDate];
if ( [futureComps day] == [currComps day] && [futureComps month] == [currComps month] && [futureComps year] == [currComps year] )
return futureDate;
daysCounter++;
} while (daysCounter < 10); // just a double check
return nil; // double check - should not get to this
}