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
中启动计时器当单击某个视图进行测试时,我调用了此方法。
-(void)clickSomthing: (UITapGestureRecognizer *)recognizer {
int i = 0;
while ([timer isValid])
{
NSLog(@"timer valid");
}
首先,当加载视图时,会触发计时器计数,我可以看到实际倒计时的次数,但是当我点击与方法相关的任何视图时,单击“#Something"计时器不会倒计时实际停止。
我真正想做的是我希望计时器继续运行,直到它达到零,无论是何时或循环。实际上,我试图基于计时器停止我的游戏,但游戏确实需要一些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];
});
}
}
});
}