如何暂停NSTimer



我有一个使用计时器的游戏。我想让用户可以选择一个按钮,它会暂停计时器,当他们再次单击该按钮时,它会取消暂停计时器。我已经有了定时器的代码,只需要一些暂停定时器和双操作按钮的帮助。

计时器代码:

-(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中没有暂停和恢复功能。你可以像下面的代码一样暗示它。

- (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;
}

最新更新