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?
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:
Then on your background thread call this when you want to cancel the timeout: