开发者

Stopping a 'performSelector afterDelay' before it fires

开发者 https://www.devze.com 2023-02-22 04:13 出处:网络
I start a repeating NSTimer after a 4 second delay using the following code: - (void)view开发者_如何转开发DidLoad {

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

- (void)view开发者_如何转开发DidLoad {
    [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!


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.


[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


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消