Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a 'performSelector afterDelay' before it fires

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!

like image 796
Timbo Avatar asked Apr 06 '11 08:04

Timbo


1 Answers

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.

like image 94
Jhaliya - Praveen Sharma Avatar answered Nov 03 '22 23:11

Jhaliya - Praveen Sharma