2013-09-27 54 views
0

我想用秒和毫秒進行簡單倒計時:SS:MM。 但是,我想停止計時器或在計時器到達0:00時執行某些操作。 目前計時器工作,但它不會在0:00停止。我可以讓秒停,但不是毫秒。哪裏不對?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 
      //Also, are you sure you want to do [self setTimer] again 
      //before checking if there are any lives left? 

      [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) { 
       [self performSelector:@selector(stopped) withObject:nil]; 

      } 
      else {[self setTimer]; } 
     } 
     else 

      tmp.milisecondsCount = 99; 
    } 


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

    timeLabel.text = timerOutput; 






} 



-(void) stopped { 
    NSLog(@"Stopped game"); 
    timeLabel.text = @"0:00"; 

} 
+0

也許這裏有一些幫助:http://stackoverflow.com/questions/15311289/nstimer-creating-a-timer-countdown – Woodstock

+0

我不明白,誰會upvote這樣的問題? – micantox

回答

1

好吧。你做

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

而且正確的

if ((tmp.secondsCount == 0) && tmp.milisecondsCount == 0) { 
    //stuff 
} 

怎麼可能它曾經發生他們都是0,如果,只要milisecond達到0,你把它恢復到100後?

編輯:難道不是一樣的東西:

if(tmp.milisecondsCount < 0){ 
    tmp.secondsCount -= 1; 
    if (tmp.secondsCount == 0){ 
     //Stuff for when the timer reaches 0 
     //Also, are you sure you want to do [self setTimer] again 
     //before checking if there are any lives left? 
    } 
    else 
     tmp.milisecondsCount = 99; 
} 
+0

但是,你對我的問題有某種解決方案嗎?否則我無法使它工作。 –

+0

好的,編輯我的問題,看看 – micantox

+0

謝謝!它現在似乎工作,但是,我的倒計時過早停止1秒?在最後的100毫秒之前可以「跑掉」,你知道爲什麼嗎? –

0

在代碼中,第一個條件得到滿足

if(tmp.milisecondsCount == 0){ 
    tmp.milisecondsCount = 100; 

,使下一個條件statment

&& tmp.milisecondsCount == 0 

決不會真正。