Question

For periodic operations that should occur on a background thread I would normally use an NSTimer. I wondered if there are any drawbacks to using gcd for the same purpose:

  //Set up a dispatch queue owned by an instance of the class. (ie in init). 
  dispatch_queue_t backgroundQueue = dispatch_queue_create("some.queue", 
       DISPATCH_QUEUE_SERIAL);

- (void)scheduleRefresh
{

    __weak id weakSelf = self;        
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 120 * NSEC_PER_SEC), 
        backgroundQueue, ^
    {
        //Do some recurring task. 

       //Now, schedule again, by calling recursively, unless weakSelf is nil
       [weakSelf scheduleRefresh] 
    });
}
Was it helpful?

Solution

You can't cancel the delayed block execution (without writing some additional wrapper code). With a timer you just invalidate.

The block retains it's contents so you need to actively think about that and (potentially) write extra code to deal with it.

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