如何暂停NSTimer?

我有一个使用计时器的游戏。 我想这样做,用户可以select一个button,并暂停该计时器,当他们再次点击该button,它将取消暂停该计时器。 我已经有了代码到计时器,只需要一些帮助暂停计时器和双动button。

代码到定时器:

-(void)timerDelay { mainInt = 36; timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownDuration) userInfo:nil repeats:YES]; } -(void)countDownDuration { MainInt -= 1; seconds.text = [NSString stringWithFormat:@"%i", MainInt]; if (MainInt <= 0) { [timer invalidate]; [self delay]; } } 

这很容易。

 // Declare the following variables BOOL ispaused; NSTimer *timer; int MainInt; -(void)countUp { if (ispaused == NO) { MainInt +=1; secondField.stringValue = [NSString stringWithFormat:@"%i",MainInt]; } } - (IBAction)start1Clicked:(id)sender { MainInt=0; timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countUp) userInfo:Nil repeats:YES]; } - (IBAction)pause1Clicked:(id)sender { ispaused = YES; } - (IBAction)resume1Clicked:(id)sender { ispaused = NO; } 

NSTimer中没有暂停和恢复function。 你可以像下面的代码一样来实现它。

 - (void)startTimer { m_pTimerObject = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(fireTimer:) userInfo:nil repeats:YES]; } - (void)fireTimer:(NSTimer *)inTimer { // Timer is fired. } - (void)resumeTimer { if(m_pTimerObject) { [m_pTimerObject invalidate]; m_pTimerObject = nil; } m_pTimerObject = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(fireTimer:) userInfo:nil repeats:YES]; } - (void)pauseTimer { [m_pTimerObject invalidate]; m_pTimerObject = nil; }