xonegirlz
xonegirlz

Reputation: 8977

cancelPreviousPerformRequest from background thread issue

I have the following code, which is executed when a button is pressed:

 [self performSelector:@selector(timeout:) withObject:nil afterDelay:30.0];

The issue comes in when I wanted to cancel this from a background thread:

[NSObject cancelPreviousPerformRequestsWithTarget:self];

I did this and it didn't cancel, it still calls timeout after 30 second. So my question, is there a way to cancel this from the background thread?

Upvotes: 0

Views: 981

Answers (2)

Robin Summerhill
Robin Summerhill

Reputation: 13675

From the documentation, 'This method removes perform requests only in the current run loop, not all run loops.' That means that you have to call cancelPreviousPerformRequestsWithTarget on the main thread. Use performSelectorOnMainThread:withObject:waitUntilDone: from your thread to schedule a call to cancelPreviousPerformRequestsWithTarget on the main thread.

It's a roundabout way of doing things, but should work.

Edit to show example:

The easiest way is to use a helper method:

-(void)cancelTimeout
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
}

Then on your background thread call this when you want to cancel the timeout:

[self performSelectorOnMainThread:@selector(cancelTimeout) withObject:nil waitUntilDone:NO];

Upvotes: 1

SiMet
SiMet

Reputation: 612

You can use NSTimer to call method after some time and invalidate if you want

Upvotes: 0

Related Questions