Stop "performSelector afterDelay" before it fires

I start 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!"); } 

The problem is that I may need to cancel the startTimer start up to 4 seconds. Is there any way to do this? I would prefer not to use PerformSelector in the first place (it seems dirty). If only NSTimer had something like this ...

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

... then that would be wonderful, as I could just call the following:

[myTimer invalidate];

Any help or advice is greatly appreciated =)

PS I found something called cancelPreviousPerformRequestsWithTarget in the NSObject class reference. This does not seem to be a method that I can call from where this code works. If you get back on the right track, your feedback will be welcome!

+4
source share
3 answers

Plz follow the link SP post

Stop execution of a selection function: from execution

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

The documentation for -performSelector: withObject: afterDelay: indicates methods for canceling a queue request.

+19
source

[myTimer invalidate] not working? Just keep tracking the object in your class or, for example, in a centralized repository. If you do, you can access your timer wherever you want and cancel it whenever necessary.

+1
source

Use NSTimer to fix the problem.

 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 the timer

  [self.autoTimer invalidate]; self.autoTimer = nil; 
0
source

Source: https://habr.com/ru/post/1346876/


All Articles