4

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?

Community
  • 1
  • 1
fabb
  • 11,660
  • 13
  • 67
  • 111

1 Answers1

4

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().

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • As I'm new to both `NSOperationQueue` and even more `GCD`, a rather noobish question: can I somehow use the `NSOperationQueue`, the current `NSOperation` is being executed at, as the dispatch queue for the delayed dispatch with `GCD`? – fabb Dec 30 '11 at 17:38
  • The code above does not to work with `dispatch_get_global_queue`, but it works with `dispatch_get_main_queue`. Any idea why? – fabb Jan 03 '12 at 15:18
  • I'm not very knowledge about GCD, so I don't completely understand the consequences of queuing to GCD on the retain/release process, but my guess is that your original issue was precipitated by the face that all of the objects in your NSOperation were released. If you search for issues related to using asynchronous NSURLConnection within an NSOperation, you'll see work-arounds that relate to maintaining pointers to objects, in order to keep the NSOperation from Finishing. – Rob Reuss Sep 26 '12 at 21:38
  • It's not the same, because you can later cancel a `performSelector:withObject:afterDelay:`, but you can't cancel `dispatch_after()` – user102008 Dec 19 '12 at 21:11