문제

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] 
    });
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top