Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatch_after equivalent in NSOperationQueue

I'm moving my code from regular GCD to NSOperationQueue because I need some of the functionality. A lot of my code relies on dispatch_after in order to work properly. Is there a way to do something similar with an NSOperation?

This is some of my code that needs to be converted to NSOperation. If you could provide 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)];
    }

});
like image 281
sinθ Avatar asked Mar 18 '13 15:03

sinθ


People also ask

What is the difference between GCD and Nsoperationqueue in IOS?

Grand Central Dispatch is a low-level C API that interacts directly with Unix level of the system. NSOperation is an Objective-C API and that brings some overhead with it. Instances of NSOperation need to be allocated before they can be used and deallocated when they are no longer needed.

What is Nsoperationqueue in Swift?

A queue that regulates the execution of operations.


2 Answers

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.

like image 123
gaige Avatar answered Oct 11 '22 22:10

gaige


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];
    }
);
like image 43
Jonathan Grynspan Avatar answered Oct 11 '22 22:10

Jonathan Grynspan