0

我不知道发生了什么。我正在尝试制作一个通过比较日期来工作的计时器。当我启动计时器时,有时它会工作然后随机停止,有时它只是返回 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);
}
4

2 回答 2

5

您正在currentDate从较早的日期中减去较晚的日期date。我告诉你反过来做:[[NSDate date] timeIntervalSinceDate:date]

于 2013-08-11T19:56:37.697 回答
2

timeIntervalSinceNow不叫是有原因的timeIntervalUntilNow...

也称为:如果相关日期早于当前日期/时间,则从现在开始经过的时间为负数。如果日期晚于当前日期,那将是肯定的。(只是一点逻辑和/或英语语义:))

   Earlier date      Current date
        ^                  ^
        +------------------+
              since now: (earlier date) - (current date)... that's < 0
于 2013-08-11T19:56:58.227 回答