2016-04-29 53 views
0
int maximumMinute; 

NSTimer *timer; 

- (void)startTimer: (int) minute { 
maximumMinute = minute; 
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES]; 

} 

- (void)countDown { 

maximumMinute -= 1; 
self.timerLabel.text = [NSString stringWithFormat:@"%i", maximumMinute]; 
if (maximumMinute == 0) { 
    [timer invalidate]; 
} 
} 

这是我的计时器代码,我刚开始的计时器viewDidLoad中的NSTimer不while循环

我有这样的方法被点击时只是测试的一些看法时调用倒计时。

-(void)clickSomthing: (UITapGestureRecognizer *)recognizer { 
    int i = 0; 
while ([timer isValid]) 
{ 
    NSLog(@"timer valid"); 
} 

首先,查看加载时,定时器计数被激发,我可以看到时间倒计时实际上,但是当我点击与方法“clickSomething”相关的任何观点定时器不倒计时实际上它停止。

我真的很想做的事情是,我希望计时器继续运行,直到它达到零,而不管是为了循环还是循环。实际上,我试图根据计时器来阻止我的游戏,但游戏确实需要一些while循环和for循环,这需要一段时间。

+0

您正在使用while循环锁定应用程序的主线程,使用它的整个应用程序和计时器。 –

+0

我该如何解决它?或者我想要做什么的建议? –

回答

0

您的代码锁定主线程(您绝不应该这样做),您应该使用GCD - Grand Central Dispatch在用户继续使用该应用程序时在后台进行倒计时。

-(void)clickSomthing: (UITapGestureRecognizer *)recognizer { 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ 

     int countDown = 10; // This is the countdown time 
     BOOL letTheCountDown = TRUE; 
     while (letTheCountDown) { 
      [NSThread sleepForTimeInterval:1.0]; // Count second by second 
      countDown--; 
      NSLog(@"countDown %i",countDown); 

      if (countDown == 0) { 
       letTheCountDown = FALSE;          
       dispatch_async(dispatch_get_main_queue(), ^{ 
        // Do something in main thread here. Ex: alert 
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Time is Over" delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil]; 
        [alert show]; 
       }); 
      } 

     } 

    }); 

}