iOS背景中的倒计时问题

时间:2010-07-20 17:13:50

标签: iphone objective-c ios4

这是我的代码(简化了一下)。我每秒都会触发一个NSTimer,它会从counter变量中减去一个。当应用程序进入后台时,我正在停止计数器并将计数器将达到零的时间保存到NSDefault值中。

然而,当从后台恢复应用程序时,当我从“零”时间减去当前时间时,我有时会得到太大的值。请帮我找一下这个bug?

- (void)prepareToEnterBackground {
    NSUserDefaults *defaults;
    defaults = [NSUserDefaults standardUserDefaults];

    [defaults setBool:[self timerIsRunning] forKey:@"timer_is_running"];
    [defaults setInteger:workPlayStatus forKey:@"work_play_status"];
    if ([self timerIsRunning]) {
        [defaults setFloat:([[NSDate date] timeIntervalSince1970] + (float) counter) forKey:@"timestamp_for_status_change"];
    } else {
        [defaults setFloat:0.0 forKey:@"timestamp_for_status_change"];
    }

    if (timer!=nil) {
        [timer invalidate];
        timer = nil;
    }
}

- (void)restoreFromBackground {
    NSUserDefaults *defaults;
    defaults = [NSUserDefaults standardUserDefaults];

    NSInteger remainingTimerSeconds;
    if ([defaults integerForKey:@"timer_is_running"]) {
        remainingTimerSeconds = (int) ([defaults floatForKey:@"timestamp_for_status_change"] - [[NSDate date] timeIntervalSince1970]);
        if (remainingTimerSeconds <= 0) {
            remainingTimerSeconds = 0;
        }
    } else {
        remainingTimerSeconds = 0;
    }

    if (remainingTimerSeconds > 0) {
        counter = remainingTimerSeconds;
        workPlayStatus = [defaults integerForKey:@"work_play_status"];
        timer = [NSTimer scheduledTimerWithTimeInterval:1 
            target:self
            selector:@selector(advanceTimer:)
            userInfo:nil
            repeats:YES];
    }
}

1 个答案:

答案 0 :(得分:4)

只是一个猜测 - NSTimeInterval类型被定义为double并且您在代码中使用浮点数,因此您可能会在某处溢出。尝试将float更改为double,这可能会有所帮助......