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

作者 : 开心源码 本文共1456个字,预计阅读时间需要4分钟 发布时间: 2022-05-12 共161人阅读

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

已是最前 目录 下一篇

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » iOS | 用于处理循环引用的block timer

发表回复