Reputation: 12405
I have a selector method which performs search for particular text in two different libraries in two different threads called using dispatch_async
.
Now this selector is bound to a textfield and as soon some characters change we can query the libraries for the text.
Now a search takes some time say like 0.3 - 0.4 second and if the first search is not complete before another character is entered I woould like to cancel the search and re-start with new characters in the text field.
So does calling cancelPreviousPerformRequestsWithTarget
on the selector cancel the internal threads and libraries call...?
Upvotes: 0
Views: 505
Reputation: 29926
No. cancelPreviousPerformRequestsWithTarget
has nothing to do with blocks dispatched via GCD (i.e. dispatch_async
). It cancels previous invocations of
selectors scheduled for a later time on a specific NSRunLoop
using -performSelector:withObject:afterDelay:
. Furthermore, it can't cancel those invocations if they're already in progress, it can only prevent them from starting, if they're still waiting to begin.
There is no means by which to (safely) forcibly cancel in flight operations, regardless of the method used to dispatch them. The operation has to, itself, support cancel-ability, usually by checking a flag periodically during its work, and returning early if the flag says the operation should cancel.
Because someone will inevitably come along and say that NSOperation
supports cancelation, I might as well get it out of the way now, by pointing out that NSOperation
's cancelation support still requires the operation being canceled to periodically check a flag and intentionally return early, it's just that NSOperation
has the cancelled
property which provides the flag for you. For that to be useful to you, your code has to know that it's executing as part of an NSOperation
, and it has to have a pointer to the specific NSOperation
it's executing as part of, and it still has to periodically check the cancelled
property of that NSOperation
and return early in order to "support cancellation."
There is no free lunch for cancellation on non-garbage-collected runtimes.
Upvotes: 3