倒数计时器不会停在0

时间:2013-08-14 17:35:46

标签: iphone ios objective-c nstimer nsuinteger

如果计时器在前台,我有一个完美的计时器。它完全递减并停在0.然而,当我点击主页按钮进入主屏幕,然后等待本地通知弹出,然后我点击通知,时间间隔变成42亿(限制for unsigned long int)。基本上,它不会停在0.我不知道如何解决这个问题。我试着让它成为常规的NSInteger并检查间隔是否低于0但我得到了相同的结果。

-(IBAction)startTimer:(id)sender{
    if (!timer) {
        [startButton setTitle:@"Start" forState:UIControlStateNormal];
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
       date = [NSDate date];
    } else {
        [startButton setTitle:@"Stop" forState:UIControlStateNormal];
        anotherTimeInterval = testTask.timeInterval;
        [timer invalidate];
        timer = nil;
    }

}

-(void)timerAction:(NSTimer *)t
{
    NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];
    if (testTask.timeInterval > 0){
        NSError *error;
        if (![self.context save:&error]) {
            NSLog(@"couldn't save: %@", [error localizedDescription]);
        }
        NSUInteger seconds = (NSUInteger)round(anotherTimeInterval-interval);
        NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
                            seconds / 3600, (seconds / 60) % 60, seconds % 60];
        testTask.timeInterval = seconds;
        timerLabel.text = string;
        NSLog(@"%@", string);
    } else {
        NSLog(@"timer ended");
        [self.timer invalidate];
        self.timer = nil;
        [self timerExpired];
    }
}

-(void)applicationWillResignActive:(UIApplication *)application{
    if (timer){
        UILocalNotification* localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:testTask.timeInterval];
        localNotification.alertBody = @"Time is up";
        localNotification.alertAction = @"Ok";
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    }
}

1 个答案:

答案 0 :(得分:1)

您在%02u中使用的stringWithFormat:将值解析为unsigned int。

另外,我认为这是你的问题,你在if语句中检查testTask.timeInterval,但从你在开始时得到的interval变量获得秒数。方法。 所以你总是检查以前的值,这意味着你总是落后一秒。

编辑: 你可以这样做:

NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];
if (anotherTimeInterval-interval > 0){
    ...
}

这样,您检查 new 值而不是旧值。

希望这有帮助