爲了您的計時器是準確的關閉,你應該只使用結束日期。我不確定你爲什麼要保留開始日期。
下面是用連續倒計時的例子:
// I'm assuming you want to update the countdown every seconds
// So you should set a timer like this somewhere
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick) userInfo:nil repeats:YES];
- (void)updateCountdown {
NSTimeInterval timeInterval = [endDate timeIntervalSinceNow];
unsigned int d, h, m, s;
NSTimeInterval r;
d = timeInterval/(24 * 3600);
r = timeInterval - d * 24 * 3600;
h = r/3600;
r = r - h * 3600;
m = r/60;
r = r - m * 60;
s = r;
NSString *countdown = [NSString stringWithFormat:@"%.2d:%.2d:%.2d:%.2d", d, h, m, s];
// Now you could use countdown to update the text of a UILabel
}
- (void)timerTick {
if ([endDate compare:[NSDate date]] == NSOrderedDescending) {
//endDate is later in time than "now", ie not yet reached
[self updateCountdown];
} else {
//stop the countdown
[timer invalidate];
}
}
endDate
應該是包含日期的NSDate當倒計時應達到0.1
因爲倒計時調整一次秒鐘,你不會即使系統時間或時區發生更改也會出現問題。
但是請確保您在應用程序重新啓動/關閉時正確保存並恢復endDate(即始終使用固定參考!我將使用NSDate類中的timeIntervalSinceReferenceDate和dateWithTimeIntervalSinceReferenceDate)。
我正在做你想說的話。我在db中存儲結束日期,並在重新啓動時獲取本地時間。但是當從nsdate類獲取當前時間時,如果我將時間改回2小時,當前nsdate將返回錯誤那麼結束日期和當前日期之間的差異並不如預期的那樣。問題是如何克服這個問題 – 2009-11-07 06:34:42