简体   繁体   中英

NSTimer responding to a uibutton

So, Here is the problem. I am trying to make a timer for my game however it doesnt seem to run.

I started by making a property for nstimer:

@property (nonatomic) NSTimer gameTimer;

and synthesizing it:

@synthesize gameTimer = _gameTimer; 

then I use this method to set it:

-(NSTimer *) gameTimer{
    if (_gameTimer == nil) _gameTimer = [[NSTimer alloc]init];
    return _gameTimer;
}

however when i try to start the timer through a uibutton:

- (IBAction)play:(UIButton *)sender {

    _levelNumber = 1;
    _en1v = -1;
    _en2v = 1;
    _en3v = -1;
    [self setPath];
    _gameTimer = [NSTimer timerWithTimeInterval:1.0 target:self     selector:@selector(onTimer:) userInfo:nil repeats:YES];
    self.play.hidden = TRUE;
}

it doesn't work.

I put an nslog into the onTimer: method and found out that the timer just isn't firing some how?

Am I making an obvious mistake?

You have not started the timer at all.

Use:

_gameTimer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];

And while stopping, (may be in stop: method)

[_gameTimer invalidate];
_gameTimer = nil;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM