为什么我的时间间隔得到负值?

Evi*_*gis 0 iphone objective-c nstimer countdown ios

我不知道发生了什么.我试图通过比较日期来制作一个有效的计时器.当我启动计时器时,它有时会工作,然后随机停止,有时它只返回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);
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ell 5

currentDate从之前的日期中减去了较晚的日期date.我告诉过你,反过来说:[[NSDate date] timeIntervalSinceDate:date]