2015-03-07 3 views
0

Я пытаюсь сделать таймер обратного отсчета, однако я борюсь с моим кодом. У меня есть UIDatePicker, чтобы выбрать дату для обратного отсчета, но каждый раз, когда я пытаюсь сделать обратный отсчет, секунды начинаются с 54 секунд, а не корректируются на фактическое время устройства. Код очень прост и прост, но я изо всех сил пытаюсь понять это.NSTimer не работает точно.

- (IBAction)startCountdown:(id)sender { 
if (ti == 0||ti <= 0) { 
    [self stopCountdown:self]; 
} 

//Set up a timer that calls the updateTime method every second to update the label 
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
             target:self 
             selector:@selector(updateTime) 
             userInfo:nil 
             repeats:YES]; 
} 
-(void)updateTime{ 


//Get the time left until the specified date and convert time into seconds. 
NSInteger ti = ((NSInteger)[self.datePicker.date timeIntervalSinceNow]); //this is the key part of the code. 
NSInteger seconds = ti % 60; 
NSInteger minutes = (ti/60) % 60; 
NSInteger hours = (ti/3600) % 24; 
//NSInteger days = (ti/86400); 

//Update the lable with the remaining time 
//self.countdownLabel.text = [NSString stringWithFormat:@"%02i days %02i hrs %02i min %02i sec", days, hours, minutes, seconds]; 
self.countdownLabel.text = [NSString stringWithFormat:@"%02i hrs %02i min %02i sec", hours, minutes, seconds]; 

} 

Пожалуйста, помогите мне, было бы очень признательно!

Спасибо заранее!

ответ

0

Существует более простой способ извлечения единиц времени, которые могут предотвратить ошибки в расчетах. Посмотрите на [NSCalendar components:fromDate:toDate:options:]

Это может стать:

NSDate *now = [NSDate date]; 
NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSCalendarUnit components = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 
NSDateComponents *diff = [calendar components:components fromDate:self.datePicker.date toDate:now options:0]; 
NSInteger seconds = [diff second]; 
NSInteger minutes = [diff minute]; 
NSInteger hours = [diff hour]; 
Смежные вопросы