选择 GCD 还是 NSTimer ?

在日常的开发工作中,我们经常会遇到是选择用 GCD 还是用 NSTimer,来做延迟操作的任务需求。今天,我们就来说说是选择 GCD 还是 NSTimer?

延迟操作的方案一般有三种:

1.NSObject的方法:

[self performSelector:(nonnull SEL) withObject:(nullable id) afterDelay:(NSTimeInterval)];

2.使用NSTimer的方法:

@interface NSTimer : NSObject

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

3.使用GCD的方法:

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
    });

一般情况下,我们选择使用GCD的dispatch_after。

因为如果不用GCD,编码需要注意以下三个细节:

1.必须保证有一个活跃的runloop。

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

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

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

扫描二维码关注公众号,回复: 6902584 查看本文章

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

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

不幸的是,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()以放到主线程中执行。

总结,综合以上所述,利用GCD我们也可以做一个适当的封装,得到一个用起来和 NSTimer一样方便的延迟执行方法, 希望今天的讲解能给大家带来解决问题的办法,感谢大家的阅读!

猜你喜欢

转载自www.cnblogs.com/chenjie005/p/11269191.html
gcd