2013-09-27 174 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 

决不会真正。