Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause a NSTimer? [duplicate]

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

}
like image 259
Kyle Greenlaw Avatar asked Aug 13 '13 02:08

Kyle Greenlaw


2 Answers

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;
}
like image 57
El Tomato Avatar answered Nov 18 '22 09:11

El Tomato


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;
}
like image 4
Adrian P Avatar answered Nov 18 '22 10:11

Adrian P