NSTimer 的官方推荐替代 MSWeakTimer 分析

基本介绍

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

问题的提出

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

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

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. this

invalidate必须由安装这个timer的线程发起,不然这个timer有可能不会从run loop中移除。这种状况会发生的一个状况就是: 当这个线程是由 GCD 管理的。 这是由于 NSTimer 依赖于当前线程的run loop, 而GCD彻底是另一回事, 它不能确保timer的阻塞和invalidate是由同一个线程发起的, run loop和queue将会交织在一块儿,世界就乱了...


而MSWeakTimer彻底就不是用run loop实现的,因此就不用考虑那么多了,它能够与GCD和谐共存,被任意线程 install 和 invalidate。 spa

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

相关文章
相关标签/搜索