iOS | 用于处理循环引用的block timer

摘要:iOS 10的时候NSTimer新添加了一个带block的API:+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))bloc

iOS 10的时候NSTimer新添加了一个带block的API:

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

苹果的官方文档里说,将这个timer本身作为参数传给block以此来避免循环引用:

/// - parameter: block The execution body of the timer; the timer itself is passed as the parameter to this block when executed to aid in avoiding cyclical references

有了这个API再也不需要繁琐的手动注销timer,结合weakSelf即可以轻松解决循环引用,如:

__weak typeof(self) weakSelf = self;self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {    __strong typeof(self) strongSelf = weakSelf;    [strongSelf printNum];}];

在这个API出现之前,self和timer的引用关系是:
self->timer->self

现在的引用关系是:
self->timer->weakSelf

但是只有iOS 10及之后的系统才能使用此API,而我们一般都是适配到iOS 8,所以有必要扩展一下。

如何扩展?

简单点,写个category,直接复制苹果的API进去(思考API设计的时间都省了??),而后加上前缀:

+ (NSTimer *)cq_scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block {    return [self scheduledTimerWithTimeInterval:interval target:self selector:@selector(cq_callBlock:) userInfo:[block copy] repeats:repeats];}+ (void)cq_callBlock:(NSTimer *)timer {    void (^block)(NSTimer *timer) = timer.userInfo;    !block ?: block(timer);}

你不是把timer作为参数传给block吗?那我也这样搞。

而后即可以像使用系统API那样使用了:

__weak typeof(self) weakSelf = self;self.timer = [NSTimer cq_scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *timer) {    __strong typeof(self) strongSelf = weakSelf;    [strongSelf printNum];}];

最后提供一个此timer使用的具体demo:
CaiWanFeng/CQCountDownButton

已是最前 目录 下一篇
  • 全部评论(0)
最新发布的资讯信息
【系统环境|】从谷歌到手机厂商都下决心了,要清除32位应用这匹“害群之马”(2025-10-17 05:41)
【系统环境|】Windows上使用QEMU创建aarch64(ARM64)虚拟机(2025-10-17 05:40)
【系统环境|】nodejs 如何安装在aarch64平台(2025-10-17 05:39)
【系统环境|】常用git命令-从远程更新代码合并分支、提交代码等(2025-10-17 05:38)
【系统环境|】技术干货|常用的 Git 功能和选项(2025-10-17 05:38)
【系统环境|】掌握git命令,图解一目了然(2025-10-17 05:37)
【系统环境|】总结几个常用的Git命令的使用方法(2025-10-17 05:36)
【系统环境|】这篇 Git 教程太清晰了,很多 3 年经验程序员都收藏了(2025-10-17 05:35)
【系统环境|】Git常用命令及操作指南(2025-10-17 05:35)
【系统环境|】「实用」盘点那些开发中最常用的Git命令(2025-10-17 05:34)
手机二维码手机访问领取大礼包
返回顶部