【问题标题】:Countdown timer doesn't stop at 0倒数计时器不会停在 0
【发布时间】:2013-08-14 17:35:46
【问题描述】:

如果计时器在前台,我有一个可以完美运行的计时器。完美递减,停在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];
    }
}

【问题讨论】:

    标签: iphone ios objective-c nstimer nsuinteger


    【解决方案1】:

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

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

    编辑: 你可以这样做:

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

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

    希望对你有帮助

    【讨论】:

    • 好吧,这是有道理的......所以你是说我不应该检查 testtask.interval 的值,而是检查别的东西?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多