前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS开发中利用block解决NSTimer的循环引用问题

iOS开发中利用block解决NSTimer的循环引用问题

作者头像
用户1451823
发布2018-09-13 11:15:33
7890
发布2018-09-13 11:15:33
举报
文章被收录于专栏:DannyHoo的专栏DannyHoo的专栏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1336807

循环引用问题:

将一个NSTimer对象作为一个控制器的的属性,这时当前VC对NSTimer对象进行了一次强引用。在创建NSTimer兑现的时候,NSTimer对象又将当前VC作为自己的target,这时NSTimer对象对当前VC进行了一次强引用,这样就造成了NSTimer和当前VC的循环引用,从而让VC和NSTimer都无法释放,最终导致内存泄漏。

通常代码:

我们可以为NSTimer创建一个分类,在分类中添加一个创建NSTimer对象的方法,以避免循环引用的问题。

NSTimer分类代码:

.m中的代码

可复制代码:

  • (NSTimer *)resolve_scheduledTimerWithTimeInterval:(NSTimeInterval)inerval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block{ return [NSTimer scheduledTimerWithTimeInterval:inerval target:self selector:@selector(resolve_blcokInvoke:) userInfo:block copy repeats:repeats];

}

  • (void)resolve_blcokInvoke:(NSTimer *)timer { void (^block)(NSTimer *timer) = timer.userInfo; if (block) { block(timer); }

}

使用代码:

可复制代码:

weakifySelf self.timer = [NSTimer resolve_scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *timer) { strongifySelf self doThings; NSLog(@"----------------"); }];

关于weakSelf和strongSelf:

define weakifySelf \

__weak __typeof(&*self)weakSelf = self;

define strongifySelf \

__strong __typeof(&*weakSelf)self = weakSelf;

demo地址:https://gitee.com/liangsenliangsen/nstimer_loop_reference.git

本篇文章到这里就结束了,愿大家加班不多工资多,男同胞都有女朋友,女同胞都有男朋友。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年05月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • define weakifySelf \
  • define strongifySelf \
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档