Question

I'm executing some code within some NSOperation objects managed by an NSOperationQueue. The code also contains a delayed method call using performSelector:withObject:afterDelay:.

The problem is, that the corresponding selector which should be called delayed, is not called at all.

Having read this answer to a StackOverflow question, I guess it's due to the fact that the NSOperation already has finished and its thread doesn't even exist anymore, "forgetting" the scheduled call to the selector.

How can I work around this? How can I do a delayed call to a method within an NSOperation?

Was it helpful?

Solution

One possibility would be to use Grand Central Dispatch, namely dispatch_after():

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_after(popTime, queue, ^{
    ...
});

Instead of dispatch_get_global_queue(), you can of course also create your own dispatch queue or use the main queue with dispatch_get_main_queue().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top