Here's my code (simplified a bit). I have an NSTimer firing every second which subtracts one from the counter
variable. When the app goes in the background, I'm stopping the counter and saving the time the counter would reach zero into an NSDefault value.
However, when restoring the app from background, when I开发者_Python百科 subtract the current time from the "zero" time, I sometimes get values that are too big. Help me find the bug please?
- (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];
}
}
Just a guess - NSTimeInterval
type is defined as double
and you work with floats in your code so you can possibly overflow somewhere. Try to change float
to double
, may be that will help...
精彩评论