2010-07-20 37 views
0

這是我的代碼(簡化了一下)。我有一個NSTimer每秒發射一次,從counter變量中減去一個。當應用程序在後臺運行時,我將停止計數器並將計數器達到零的時間保存爲NSDefault值。iOS中的倒計時問題

但是,當從後臺恢復應用程序時,當我從「零」時間減去當前時間,我有時會得到太大的值。請幫我找到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

哪個變量要大? – tadejsv 2010-07-20 17:22:22

回答

4

只是一個猜測 - NSTimeInterval類型被定義爲double,你在你的代碼花車工作,所以你可能溢出的地方。嘗試將float更改爲double,可能會有所幫助...

+0

非常感謝。我一定錯過了。 – winsmith 2010-07-20 18:41:13