iOS倒数计时器到特定date

我正试图让倒数计时器到一个特定的date。 我用:

-(void) viewWillAppear:(BOOL)animated { NSString *str =@"12/27/2013"; NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; [formatter setDateFormat:@"MM/dd/yyyy"]; NSDate *date = [formatter dateFromString:str]; NSTimeInterval numberOfSecondsUntilSelectedDate = [date timeIntervalSinceNow]; NSInteger numberOfDays = numberOfSecondsUntilSelectedDate / 86400; startTime = [[NSDate date] retain]; secondsLeft = numberOfDays; NSLog(@"number%f", numberOfSecondsUntilSelectedDate); [self countdownTimer]; } - (void)updateCounter:(NSTimer *)theTimer { if(secondsLeft > 0 ){ secondsLeft -- ; days = secondsLeft / 86400; NSLog(@"%d", days); hours = secondsLeft / 3600; minutes = (secondsLeft % 3600) / 60; seconds = (secondsLeft %3600) % 60; myCounterLabel.text = [NSString stringWithFormat:@"%02d Days %02d Hours %02d Minutes %02d Seconds", days, hours, minutes, seconds]; } else{ secondsLeft = 16925; } } -(void)countdownTimer{ secondsLeft = hours = minutes = seconds = 0; if([timer isValid]) { [timer release]; } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES]; [pool release]; } 

然而,这一天持续出现为0.我做错了什么?

倒数到特定date的方法是启动一个计时器,每次询问是否该date已经到来。 第二个问题是如何计算用户界面的时间分钟秒。 答案是NSDateFormatter – 绝对不是* 60或* 24math。

 @property (strong, nonatomic) NSDate *targetDate; // compute targetDate as you have it // ... self.targetDate = [formatter dateFromString:str] // start a timer [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES]; - (void)updateCounter:(NSTimer *)theTimer { NSDate *now = [NSDate date]; // has the target time passed? if ([self.targetDate earlierDate:now] == self.targetDate) { [theTimer invalidate]; } else { NSUInteger flags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; NSDateComponents *components = [[NSCalendar currentCalendar] components:flags fromDate:now toDate:self.targetDate options:0]; NSLog(@"there are %ld hours, %ld minutes and %ld seconds remaining", (long)[components hour], (long)[components minute], (long)[components second]); } } 

逻辑错误….

 -(void) viewWillAppear:(BOOL)animated { NSString *str =@"12/27/2013"; NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; [formatter setDateFormat:@"MM/dd/yyyy"]; NSDate *date = [formatter dateFromString:str]; NSTimeInterval numberOfSecondsUntilSelectedDate = [date timeIntervalSinceNow]; NSInteger numberOfDays = numberOfSecondsUntilSelectedDate / 86400; startTime = [[NSDate date] retain]; secondsLeft = numberOfSecondsUntilSelectedDate; NSLog(@"number%f", numberOfSecondsUntilSelectedDate); [self countdownTimer]; }