这是我的代码(简化了一下)。我每秒都会触发一个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];
}
}
答案 0 :(得分:4)
只是一个猜测 - NSTimeInterval
类型被定义为double
并且您在代码中使用浮点数,因此您可能会在某处溢出。尝试将float
更改为double
,这可能会有所帮助......