GCD线程与runloop中添加timer的见解

来源:互联网 发布:java intent bundle 编辑:程序博客网 时间:2024/04/30 08:06

GCD与NSTimer

很多时候,我们需要在自己的项目中重复、延迟、周期性的执行某一项任务,也可能在某一个时间点取消掉自己已经延迟或重复的任务

显而易见,延迟操作我们最经常使用的是GCD的dispatch_after,但延迟操作一共有三种方法,今天就简单说说其中的区别

1.NSObject的对象方法:

- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray<NSRunLoopMode> *)modes;- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;

2.NSTimer的类方法:

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

3.GCD的方法:

dispatch_after(dispatch_time_t when,dispatch_queue_t queue,dispatch_block_t block);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{        <#code to be executed after a specified delay#>    });

如果使用前两者,那么需要注意几个细节:

1、必须有一个活跃的runloop

performSelector和scheduledTimerWithTimeInterval方法都是基于runloop的。我们知道,当一个应用启动时,系统会开启一个主线程,并且把主线程的runloop激活,也就是run起来,并且主线程的runloop是不会停止的。所以,当这两个方法在主线程可以被正常调用。但情况往往不是这样的。实际编码中,我们更多的逻辑是放在子线程中执行的。而子线程的runloop是默认关闭的。这时如果不手动激活runloop,performSelector和scheduledTimerWithTimeInterval的调用将是无效的。

2.NSTimer的创建与撤销必须在同一个线程操作、performSelector的创建与撤销必须在同一个线程操作。

3.内存管理有潜在泄露的风险

scheduledTimerWithTimeInterval方法将target设为A对象时,A对象会被这个timer所持有,也就是会被retain一次,timer会被当前的runloop所持有。performSelector:withObject:afterDelay:方法实际上是在当前线程的runloop里帮你创建的一个timer去执行任务,所以和scheduledTimerWithTimeInterval方法一样会retain其调用对象。但是,我们往往不希望因为这些延迟操作而影响对象的生命周期,更甚至是,导致对象无法释放。举个例子:

- (void)fireTimer{    _timer = [NSTimer timerWithTimeInterval:2.0                                     target:self                                   selector:@selector(doTheJob)                                   userInfo:nil                                    repeats:YES];}- (void)cancel{    [_timer invalidate];}

你创建的对象X中有一个实例变量_timer,方法fireTimer触发一个timer,方法cancel取消这个timer。在对象X需要销毁的时候,需要将它的timer取消掉。

- (void)dealloc{    [_timer invalidate];}
但是,dealloc方法将永远不会被调用。因为timer的引用,对象X的引用计数永远不会降到0,dealloc方法也就不会被调用。这时如果不调用cancel,对象X将永远无法释放,造成内存泄露。一个对象若不调用某一个方法就会造成内存泄露,这是一个大坑,在开发中必须避免。

This method is the only way to remove a timer from an NSRunLoop object. The NSRunLoop object removes its strong reference to the timer, either just before the invalidate method returns or at some later point.

If it was configured with target and user info objects, the receiver removes its strong references to those objects as well.

You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.

上面摘自苹果官方文档对invalidate方法的解释。可以看到,当一个timer被schedule的时候,timer会持有target对象,NSRunLoop对象会持有timer。当invalidate被调用时,NSRunLoop对象会释放对timer的持有,timer会释放对target的持有。除此之外,我们没有途径可以释放timer对target的持有。所以解决内存泄露就必须撤销timer,若不撤销,target对象将永远无法释放。

若使用dispatch_after,系统会帮我们处理线程级的逻辑,这样也我们更易于享受系统对线程所做的优化。除此之外,我们不用关心runloop的问题。并且调用的对象也不会被强行持有,这样上述的内存问题也不复存在。当然,需要注意block会持有其传入的对象,但这可以通过weakself解决。所以在这种延迟操作方案中,使用dispatch_after更佳。

但是呢,dispatch_after有个致命的弱点:dispatch_after一旦执行后,就不能撤销了。而performSelector可以使用cancelPreviousPerformRequestsWithTarget方法撤销,NSTimer也可以调用invalidate进行撤销。(注意:撤销任务与创建timer任务必须在同一个线程,即同一个runloop)所以我们还是得用NSTimer或者performSelector吗?

NO,其实GCD也有timer的功能。用GCD来实现一个timer:

这样我们就规避了NSTimer的三个缺陷。

到这里问题基本得到了解决,但是我们还可以做的更好

1.GCD的timer使用的API比较冗余,每次使用都会copy代码。2.没有repeats的选项,若只想执行一次还得自己写标记位控制。这些问题我们都可以封装成一个统一的API:


这样,外部只需调用这个两个接口,用起来和NSTimer一样方便

上面的代码就创建了一个名叫myTimer的timer,这个timer将在2 seconds后执行一个block,随后timer自动停止并被释放。当然,如果repeats参数传入的是YES,那么这么timer会一个周期接一个周期的执行,直到你cancel掉这个timer。


当然,你可以在self对象的dealloc方法里面做cancel,这样保证了timer恰好运行于整个对象的生命周期中。这是NSTimer和performSelector所做不到的事情。你也可以通过queue参数控制这个timer所添加到的线程,也就是action最终执行的线程。传入nil则会默认放到子线程中执行。UI相关的操作需要传入dispatch_get_main_queue()以放到主线程中执行。


Well, we can actually do even better.

注意到,我们经常遇到的场景是,在开始新一次计时的时候,取消掉上一次的计时。也就是每次schedule之前先cancel。这部分对任务处理的能力,也是可以集成到我们的组件中的。我们可以向外部提供一个枚举类型的选项,以选择其对任务的处理类型:

或者场景是,在开始新一次计时的时候,取消上一次的计时,但是将上一次计时的任务,合并到新的一次计时中,最终一并执行。

针对这两种场景,GL_GCDTimerManager提供了两个option选项:

如果你不care这些使用场景的话,默认使用AbandonPreviousAction就行了。需要注意的是,同一个timer建议保持同一个任务处理方式,即相同的ActionOption,如果需要切换option,请注意一下切换的衔接问题。

大家也可以自行去对actionOption做扩展,以满足常见的使用场景。

综上,选择使用GCD的技术有助于我们提高代码的健壮性与稳定性。

0 0