Search code examples
iosnstimer

How can I set a NSTimer based on what button is pressed?


I have a game where I set a timer.

-(void)setTimer{
self->mTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self   selector:@selector(buttonNotPushed) userInfo: nil repeats:NO];
}

-(void)resetTimer{
[self->mTimer invalidate];
self->mTimer = nil;
}

Currently, when a user hits the Play button, the timer will be 5 seconds. There are other buttons which every time they are pressed I run

- (IBAction)buttonPressed:(id)sender {

if ([condition]) {
[self resetTimer];
[self setTimer];
}
else ([self gameOver]);
}

I would like to create a practice/kid mode where the timer is 10 seconds. Is there a shorter way I can do this besides replicating the whole game again on another viewController and setting the timer?


Solution

  • Rather than using an explicit 5.0 in setTimer, create an integer property and reference that. So, create interval in your @interface

    @property (nonatomic) CGFloat interval;
    

    And then set it to 5.0 or 10.0 as appropriate. And then your setTimer is merely:

    - (void)setTimer {
        mTimer = [NSTimer scheduledTimerWithTimeInterval:self.interval target:self selector:@selector(buttonNotPushed) userInfo: nil repeats:NO];
    }