NSTimer 的官方推荐替代 MSWeakTimer 分析

基本介绍

线程安全的MSWeakTimer是NSTimer的替代品,最基本的特点是它不会 retain target 以及支持GCD queues。

问题的提出

关于 NSTimer 中 target 的生命周期问题,啸笑天同学在他的博客中说的很清楚了。当 repeat 为 YES 时NSTimer 会 retains 它的 target,那么target的生命周期就成了问题,完全的交给了这个timer,只有当timer 调用invalidate后 dealloc 才有机会发生

另一个问题是GCD,在苹果的官方文档中说的很清楚:

Special Considerations

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的线程发起,否则这个timer有可能不会从run loop中移除。这种情况会发生的一个情况就是: 当这个线程是由 GCD 管理的。 这是因为 NSTimer 依赖于当前线程的run loop, 而GCD完全是另外一回事, 它不能确保timer的阻塞和invalidate是由同一个线程发起的, run loop和queue将会交织在一起,世界就乱了...


而MSWeakTimer完全就不是用run loop实现的,所以就不用考虑那么多了,它可以与GCD和谐共存,被任意线程 install 和 invalidate。

那它是如何使用和实现的呢,稍后分析它的源码...


转载于:https://my.oschina.net/grant110/blog/161332

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值