0

如果计时器在前台,我有一个计时器可以完美运行。完美递减,停在0。但是,当我点击home键进入主屏幕,然后等待本地通知弹出,然后我点击通知时,时间间隔变成了42亿(限制对于无符号长整数)。基本上,它不会停在 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];
    }
}
4

1 回答 1

1

%02u您在将stringWithFormat:值解析为无符号整数。

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

编辑:你可以这样做:

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

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

希望这可以帮助

于 2013-08-14T17:42:25.303 回答