這裏是我的代碼:的NSDate倒計時與NSInterval
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:currDate];
NSDate *now = [NSDate date];
int interval = 1*60; // one minute (minutes*60)
long int nowSeconds = (long int) [now timeIntervalSince1970];
int secondsLeft = interval - (nowSeconds % interval);
NSDate *nextIntervalDate = [NSDate dateWithTimeIntervalSince1970:nowSeconds+secondsLeft];
NSString *nextTrigger = [dateFormatter stringFromDate:nextIntervalDate];
timeRemaining.text = [NSString stringWithFormat:@"%02d:%02d", secondsLeft/60, secondsLeft%60];
NSLog([NSString stringWithFormat:@"%@:%@", currentTime, nextTrigger]);
if ([currentTime isEqualToString:nextTrigger]) {
}
問題是, '如果([currentTime的isEqualToString:nextTrigger])' 從來都不是平等的。因爲nextTrigger在它們相等之前更改爲下一個時間段。這裏是NSLog:
2013-01-17 15:54:59.987 app[35987:c07] 15:54:59:15:55:00
2013-01-17 15:54:59.997 app[35987:c07] 15:54:59:15:55:00
2013-01-17 15:55:00.007 app[35987:c07] 15:55:00:15:56:00 <----RIGHT HERE
2013-01-17 15:55:00.016 app[35987:c07] 15:55:00:15:56:00
我的代碼的nextTrigger基本上是當前時間的最近一個分鐘的四捨五入。此外,整個代碼段每隔1秒鐘處於一個重複的NSTimer中。
我該如何解決這個問題?
你能解釋一下你的代碼是應該做的? –
基本上,當我按下一個按鈕時,它會設置一個NSTimer來每隔1秒觸發我的代碼。它正在等待下一個「回合時間」。比如,如果是10:31:23那麼它會倒數到10:32:00。如果時間是01:10:01那麼它會倒計時到01:11:00 – objectiveccoder001
然後,當倒計時結束時,如果([currentTime isEqualToString:nextTrigger]),其他代碼將觸發。 – objectiveccoder001