Dispatch_after equivalent in NSOperationQueue

I am moving my code from a regular GCD to NSOperationQueue because I need some functions. Most of my code relies on dispatch_after to work properly. Is there a way to do something similar with NSOperation ?

This is part of my code that needs to be converted to NSOperation . If you could give an example of converting it using this code, that would be great.

 dispatch_queue_t queue = dispatch_queue_create("com.cue.MainFade", NULL); dispatch_time_t mainPopTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeRun * NSEC_PER_SEC)); dispatch_after(mainPopTime, queue, ^(void){ if(dFade !=nil){ double incriment = ([dFade volume] / [self fadeOut])/10; //incriment per .1 seconds. [self doDelayFadeOut:incriment with:dFade on:dispatch_queue_create("com.cue.MainFade", 0)]; } }); 
+16
ios objective-c xcode grand-central-dispatch nsoperationqueue
Mar 18 '13 at 15:31
source share
5 answers

NSOperationQueue does not have any synchronization mechanism in it. If you need to set up such a delay and then complete the operation, you need to schedule NSOperation from dispatch_after to handle both the delay and the final NSOperation code.

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

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

+25
Mar 18 '13 at 15:39
source share

You can use dispatch_after() with a global queue and then schedule the operation in your operation queue. Blocks passed to dispatch_after() are not executed after the specified time, they are just scheduled after this time.

Something like:

 dispatch_after ( mainPopTime, dispatch_get_main_queue(), ^ { [myOperationQueue addOperation:theOperationObject]; } ); 
+3
Mar 18 '13 at 15:36
source share

You can do an NSOperation that sleeps: MYDelayOperation. Then add it as a dependency for your real work.

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

Using:

 NSOperation *theOperationObject = ... MYDelayOperation *delayOp = [[MYDelayOperation alloc] initWithDelay:5]; [theOperationObject addDependency:delayOp]; [myOperationQueue addOperations:@[ delayOp, theOperationObject] waitUntilFinished:NO]; 
+1
Apr 11 '14 at 6:55
source share
 [operationQueue performSelector:@selector(addOperation:) withObject:operation afterDelay:delay]; 
0
Oct 24 '16 at 12:55
source share

Swift 4:

 DispatchQueue.global().asyncAfter(deadline: .now() + 10 { [weak self] in guard let 'self' = self else {return} self. myOperationQueue.addOperation { //...code... } } 
0
Feb 07 '19 at 9:49
source share



All Articles