dispatch_after equivalent in NSOperationQueue dispatch_after equivalent in NSOperationQueue ios ios

dispatch_after equivalent in NSOperationQueue


NSOperationQueue doesn't have any timing mechanism in it. If you need to set up a delay like this and then execute an operation, you'll want to schedule the NSOperation from the dispatch_after in order to handle both the delay and making the final code an NSOperation.

NSOperation is designed to handle more-or-less batch operations. The use case is slightly different from GCD, and in fact uses GCD on platforms with GCD.

If the problem you are trying to solve is to get a cancelable timer notification, I'd suggest using NSTimer and invalidating it if you need to cancel it. Then, in response to the timer, you can execute your code, or use a dispatch queue or NSOperationQueue.


You can keep using dispatch_after() with a global queue, then schedule the operation on your operation queue. Blocks passed to dispatch_after() don't execute after the specified time, they are simply scheduled after that time.

Something like:

dispatch_after(    mainPopTime,    dispatch_get_main_queue(),    ^ {        [myOperationQueue addOperation:theOperationObject];    });


You could make an NSOperation that performs a sleep: MYDelayOperation. Then add it as a dependency for your real work operation.

@interface MYDelayOperation : NSOperation...- (void)main{    [NSThread sleepForTimeInterval:delay]; // delay is passed in constructor}

Usage:

NSOperation *theOperationObject = ...MYDelayOperation *delayOp = [[MYDelayOperation alloc] initWithDelay:5];[theOperationObject addDependency:delayOp];[myOperationQueue addOperations:@[ delayOp, theOperationObject] waitUntilFinished:NO];