2013-09-27 73 views
0

我有一個NS定時器倒計時,它完美地工作得很好,這要歸功於你的答案。但是,我的計時器跳過了最後一秒,因此它不會計算最後0秒:99毫秒。我的代碼有什麼問題嗎?最好的祝福!NSTimer倒計時跳過上一秒(不使用最後毫秒)

-(void) setTimer { 
    MySingletonCenter *tmp = [MySingletonCenter sharedSingleton]; 
    tmp.milisecondsCount = 99; 
    tmp.secondsCount = 2; 



    tmp.countdownTimerGame = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(timerRun) userInfo:nil repeats:YES]; 


} 

-(void) timerRun { 
    MySingletonCenter *tmp = [MySingletonCenter sharedSingleton]; 
    tmp.milisecondsCount = tmp.milisecondsCount - 1; 



    if(tmp.milisecondsCount == 0){ 
     tmp.secondsCount -= 1; 


     if (tmp.secondsCount == 0){ 

      //Stuff for when the timer reaches 0 

      [tmp.countdownTimerGame invalidate]; 
      tmp.countdownTimerGame = nil; 
      tmp.lives = tmp.lives - 1; 
      NSString *newLivesOutput = [NSString stringWithFormat:@"%d", tmp.lives]; 
      livesLabel.text = newLivesOutput; 
      if (tmp.lives == 0) { 
       timeLabel.text = @"0:00"; 
       [self performSelector:@selector(stopped) withObject:nil afterDelay:2.0]; 

      } 
      else {[self setTimer]; } 
     } 
     else 

      tmp.milisecondsCount = 99; 
    } 


    NSString *timerOutput = [NSString stringWithFormat:@"%2d:%2d", tmp.secondsCount, tmp.milisecondsCount]; 

    timeLabel.text = timerOutput; 






} 

回答

0

嘗試改變這種

-(void) setTimer { 
    MySingletonCenter *tmp = [MySingletonCenter sharedSingleton]; 
    tmp.milisecondsCount = 100;// Change this from 99 to 100 
    tmp.secondsCount = 2; 



    tmp.countdownTimerGame = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(timerRun) userInfo:nil repeats:YES]; 


} 
+0

我已經試過了。但它不起作用。無論如何感謝您的回答。 –

0

一開始,擺脫

else {[self setTimer]; } 

否則,你每次重新啓動計時器,選擇火災。

下一頁:交換這兩個圍繞

tmp.secondsCount -= 1; 

    if (tmp.secondsCount == 0){ 

else { 
    tmp.secondsCount -= 1; 
    tmp.milisecondsCount = 99; 
} 

像這樣:

-(void) timerRun { 
    MySingletonCenter *tmp = [MySingletonCenter sharedSingleton]; 
    tmp.milisecondsCount = tmp.milisecondsCount - 1; 

    if(tmp.milisecondsCount == 0){ 

     if (tmp.secondsCount == 0){ 

      //Stuff for when the timer reaches 0 

      [tmp.countdownTimerGame invalidate]; 
      tmp.countdownTimerGame = nil; 
      tmp.lives = tmp.lives - 1; 
      NSString *newLivesOutput = [NSString stringWithFormat:@"%d", tmp.lives]; 
      livesLabel.text = newLivesOutput; 
      if (tmp.lives == 0) { 
       timeLabel.text = @"0:00"; 
       [self performSelector:@selector(stopped) withObject:nil afterDelay:2.0]; 

      } 
     } 
     else 
     { 
      tmp.milisecondsCount = 99; 
      tmp.secondsCount -= 1; 
     } 
    } 

    NSString *timerOutput = [NSString stringWithFormat:@"%2d:%2d", tmp.secondsCount, tmp.milisecondsCount]; 

    timeLabel.text = timerOutput; 

}