Dan Rosenstark
Dan Rosenstark

Reputation: 69777

Why doesn't `cancelPreviousRequestsWithTarget` cancel an NSTimer?

I schedule an NSTimer instance like this:

    [NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(someMethod) userInfo:nil repeats:YES];

I am able to call invalidate on my NSTimer to stop it from firing, but

    [NSTimer cancelPreviousPerformRequestsWithTarget:self];

does not stop the timer. I have checked and [NSRunLoop currentRunLoop] is exactly the same (as expected, these are in responses to user clicks) and of course the self instance is always the same. Why doesn't cancel cancel?

Upvotes: 0

Views: 867

Answers (1)

Peter Hosey
Peter Hosey

Reputation: 96353

cancelPreviousPerformRequestsWithTarget: is an NSObject method, not an NSTimer method, and it is the inverse of NSObject's performSelector: methods.

[NSTimer cancelPreviousPerformRequestsWithTarget:self] is the same as [NSObject cancelPreviousPerformRequestsWithTarget:self], and what it cancels is any previous [self performSelector:… withObject:… afterDelay:…] messages. It has nothing to do with any NSTimer instances.

Sending the message to the NSTimer class rather than the NSObject class works the same way that sending alloc to a class does. No classes override it; it works because NSObject's implementation is inherited, and it does the same thing for the same reason.

Upvotes: 3

Related Questions