How to pause a NSTimer? [duplicate]

2019-03-21 12:22发布

问题:

This question already has an answer here:

  • How can I programmatically pause an NSTimer? 15 answers

I have a game which uses a timer. I want to make it so the user can select a button and it pauses that timer and when they click that button again, it will unpause that timer. I already have code to the timer, just need some help with the pausing the timer and the dual-action button.

Code to timer:

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

}

回答1:

That's very easy.

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


回答2:

There is no pause and resume functionality in NSTimer. You can impliment it like below code.

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