5
votes

I start a repeating NSTimer after a 4 second delay using the following code:

- (void)viewDidLoad {
    [self performSelector:@selector(startTimer) withObject:self afterDelay:4];
}
- (void)startTimer {
    NSTimer *mytimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
}
- (void)doSomething {
    NSLog(@"What up!");
}

Problem is I may need to cancel startTimer from being called before the 4 seconds is up. Is there a way of doing this? I'd actually prefer to not use the performSelector in the first place (seems messy). If only NSTimer had something along the lines of this…

NSTimer *mytimer = [NSTimer scheduledTimerWithTimeInterval:1.0 afterDelay:4.0 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];

…then that would be perfect as I could just call the following:

[myTimer invalidate];

Any help or tips are much appreciated =)

P.S. I've found something called cancelPreviousPerformRequestsWithTarget in the NSObject class reference. Doesn't seem to be a method I can call from where this code runs however. If that's getting back on the right track your feedback is welcome!

3
you can use a non-repeating timer to fire off the repeating timerNick Moore
Nice one Nick, a much cleaner option. Thanks! Pity I can't mark your comment as the answer. I'll have to mark the next nearestTimbo

3 Answers

21
votes

Plz go through the SP post link

Stopping a performSelector: from being performed

[NSObject cancelPreviousPerformRequestsWithTarget:self
                                         selector:@selector(sr)
                                           object:nil];

The documentation for -performSelector:withObject:afterDelay: points you to the methods for canceling a queued perform request.

1
votes

[myTimer invalidate] doesn't work? Just keep a track of the object in your class, or in a centralized store for example. If you do so, you could access your timer from everywhere you want, and invalidate it whenever it is needed

0
votes

Use the NSTimer to fix issue.

self.autoTimer = [NSTimer timerWithTimeInterval:3.0 target:self
selector:@selector(connectionTimeout:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:autoTimer
forMode:NSDefaultRunLoopMode];

and call when you want to stop timer

 [self.autoTimer invalidate];

 self.autoTimer = nil;