我不知道发生了什么。我试图通过比较日期来制作一个有效的计时器。当我启动计时器时,它有时会工作,然后随机停止,有时它只返回timeInterval的值。当时间间隔为负时,它似乎只能正常工作。这是我的方法:
-(IBAction)startTimer:(id)sender{
if (timer == nil) {
[startButton setTitle:@"Start" forState:UIControlStateNormal];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
date = [NSDate dateWithTimeIntervalSinceNow:testTask.timeInterval]; //instance variable
} else {
[startButton setTitle:@"Stop" forState:UIControlStateNormal];
[timer invalidate];
timer = nil;
}
}
-(void)timerAction:(NSTimer *)t
{
NSDate *currentDate = [NSDate date];
NSTimeInterval updatedTimeInterval = [date timeIntervalSinceDate:currentDate];
if (updatedTimeInterval > 0){
if (self.timer)
{
[self timerExpired];
[self.timer invalidate];
self.timer = nil;
}
}
else
{
testTask.timeInterval = updatedTimeInterval;
NSLog(@"%.2f", testTask.timeInterval);
NSError *error;
if (![self.context save:&error]) {
NSLog(@"couldn't save: %@", [error localizedDescription]);
}
}
NSUInteger seconds = (NSUInteger)round(testTask.timeInterval);
NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
timerLabel.text = string;
NSLog(@"%f", testTask.timeInterval);
}
答案 0 :(得分:5)
您从较早的currentDate
中减去较晚的日期date
。我告诉过你这样做:[[NSDate date] timeIntervalSinceDate:date]
答案 1 :(得分:2)
有一个原因timeIntervalSinceNow
未被称为timeIntervalUntilNow
...
也称为:如果相关日期早于当前日期/时间,则过去的时间现在为负数。如果日期晚于当前日期,那将是积极的。 (只是一点逻辑和/或英语语义:))
Earlier date Current date
^ ^
+------------------+
since now: (earlier date) - (current date)... that's < 0