使用dispatch_after作为NSTimer的替代方案来进行定期计划操作

3

对于应该在后台线程上定期执行的操作,我通常会使用NSTimer。我想知道是否使用GCD有任何缺点:

  //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] 
    });
}
1个回答

8

你不能取消延迟块执行(不编写一些额外的包装代码)。使用计时器,只需使其无效。

该块保留其内容,因此您需要积极考虑这一点并(可能)编写额外的代码来处理它。


当然。实际上,我之前提供的示例已经有泄漏了。我想现在我已经修复了它。不过NSTimer仍然更好。 - Jasper Blues

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接