封装一个GCD定时器,彻底解决定时器循环引用、释放时机问题

相信大家在开发中都会使用到定时器, 但又常常对定时器的循环引用问题, NSTimer 释放时机的选择上,劳神费力! 读了本文,这些再也不是问题! 
关于 NSTimer 创建定时器的方法,我就不多做描述了,网上很多例子,但也总觉得很麻烦。本文主要讲使用GCD的方法。

今天在重构代码的时候,发现项目中好几个地方都用到了定时器,就想着封装一个定时器的方法,以后用着方便,也可以丰富自己的工具类库;写的时候,发现 GCD定时器方法并不被执行,细看之下感觉跟以前写的也没什么区别啊,但为什么就没有执行呢?

void dispatchTimer(double timeInterval, void (^handler)())
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(timer,dispatch_time(DISPATCH_TIME_NOW, 0),1.0*NSEC_PER_SEC, 0); 
    dispatch_source_set_event_handler(timer, ^{

            dispatch_async(dispatch_get_main_queue(), ^{
                handler();
            });
    });
    dispatch_resume(timer);
}

细想一下,原来是因为 timer 是个局部变量,当函数执行完之后,会被自动释放,也就不会再执行handler的方法了;忽略了以前在控制器中实现的时候 都会用一个属性来记录下 timer;

网上的一些文章也大都会说 ,要用 全局变量记录下timer,防止timer被释放,其实不然。 
http://www.cnblogs.com/dongjue/p/5804521.html 
http://www.jianshu.com/p/3a300fefa627

如何保证 在执行 handler 时 timer 不被释放呢? 我需要对 timer 有一个强引用, 如果按原来的思路在用到定时器的类里用属性记录下timer,把timer作为参数传入,我就需要每次调用这个函数的时候先创建好一个 定时器,那么封装的这个方法也就没有什么意义了。

后来想到一个方法: 给回调 handler 里添加一个 dispatch_source_t timer 参数,在 dispatch_source_set_event_handler 的block里回调 handler时将局部变量 timer 回传; 这个时候dispatch_source_set_event_handler的 block 相当于对 timer 进行了一次强引用,这样一来 timer 也就不会被过早释放了; 
如有对 block 内存管理不慎明白的可以看一下这篇文章 
block对外部变量的内存管理

void dispatchTimer(double timeInterval,void (^handler)(dispatch_source_t timer))
{
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
        dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), (uint64_t)(timeInterval *NSEC_PER_SEC), 0);
        // 设置回调
        dispatch_source_set_event_handler(timer, ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                //编译时block会对timer对象强引用,使timer不会被过早释放
                if (handler) handler(timer);
            });
        });
        // 启动定时器
        dispatch_resume(timer);
}

在使用的时候才发现,handler 里添加的那个 dispatch_source_t timer 参数,原来也是必须要有的,我需要 timer对象 来结束定时器或销毁定时器。o(╯□╰)o 啊,原以为解决了一个问题,没想到这是必须的一个参数。o(╯□╰)o o(╯□╰)o o(╯□╰)o

后来考虑到,当使用定时器的对象销毁的时候,可能并没有手动对定时器进行释放,于是又完善了一下, 添加了一个 target 参数,当 target 销毁时,就将 定时器销毁。哈哈,终于功德圆满了。

先看看使用效果吧: 

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    __block int timeCount = 60;
    dispatchTimer(self, 1.0, ^(dispatch_source_t timer) {

        if (timeCount < 0) {
            dispatch_source_cancel(timer);
        } else {
            NSLog(@"%d", timeCount);
            timeCount -= 5;
        }
    });

}
  • 注意:

调用 dispatch_source_cancel(timer); 就会将 timer 对象销毁,唯一要考虑的就是 timer 的结束时机;即使你不主动释放timer, 也不会造成循环引用哦 O(∩_∩)O~

上源码:

扫描二维码关注公众号,回复: 2798295 查看本文章
/**
 开启一个定时器

 @param target 定时器持有者
 @param timeInterval 执行间隔时间
 @param handler 重复执行事件
 */
void dispatchTimer(id target, double timeInterval,void (^handler)(dispatch_source_t timer))
{
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
        dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), (uint64_t)(timeInterval *NSEC_PER_SEC), 0);
        // 设置回调
    __weak __typeof(target) weaktarget  = target;
        dispatch_source_set_event_handler(timer, ^{
            if (!weaktarget)  {
                dispatch_source_cancel(timer);
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (handler) handler(timer);
                });
            }
        });
        // 启动定时器
        dispatch_resume(timer);
}
  •  

将此函数copy到你的工具类中就可以放心使用了。

妈妈再也不用担心 我的定时器的循环引用问题了! 哈哈,有没有很 激动!

猜你喜欢

转载自blog.csdn.net/runtime233/article/details/81296771