NSTimer 销毁问题 和 iOS中控制器的释放问题

俗话说的好,前人栽树后人乘凉,最近看了很多博文,不少博文提到了NSTimer的销毁问题, 之前我都没怎么注意,现在对照着文章一一实践发现坑还真不少。下面是我读到的几篇博文分享给大家

@啸笑天的NSTimer
@庞海礁的个人空间
@汪海的实验室「iOS 中的 NSTimer」

这几篇文章阐述了NSTimer的销毁问题,并且都给出解决方案

这里就提供一个简洁的方案,是由啸笑天提供的

+ (NSTimer *)ez_scheduledTimerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats
{
    void (^block)() = [inBlock copy]; NSTimer * timer = [self scheduledTimerWithTimeInterval:inTimeInterval target:self selector:@selector(__executeTimerBlock:) userInfo:block repeats:inRepeats]; return timer; } + (NSTimer *)ez_timerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)())inBlock repeats:(BOOL)inRepeats { void (^block)() = [inBlock copy]; NSTimer * timer = [self timerWithTimeInterval:inTimeInterval target:self selector:@selector(__executeTimerBlock:) userInfo:block repeats:inRepeats]; return timer; } + (void)__executeTimerBlock:(NSTimer *)inTimer; { if([inTimer userInfo]) { void (^block)() = (void (^)())[inTimer userInfo]; block(); } }
啸笑天解决方案的github地址

https://github.com/easyui/EZToolKit/blob/master/EZToolKit/EZCategory/NSTimer%2BEZ_Helper.m

提醒

上面的解决办法,只是解决了target的强引用问题,但是NSTimer销毁还是得自己在使用的viewController的dealloc方法中销毁

- (void)dealloc {
    if ([self.timer isValid]) {
        [self.timer invalidate]; self.timer = nil; } }

或者你有更好的办法,请拼命的@我

NSTimer的创建方式

创建方式有2种

1.这种创建方式,会主动添加到主循环中,即默认会执行,但当用户按住其他控件的时候,它就会停止执行,当放开控件,它才继续执行
__weak typeof(self) weakSelf = self;
self.timer = [NSTimer ez_scheduledTimerWithTimeInterval:1.f block:^{
    NSLog(@"nextPage"); [weakSelf nextPage]; } repeats:YES];
2.这种创建方式,不会主动添加到主循环中,得手动添加,有两种执行模式
NSRunLoopCommonModes 按住其它控件,不会停止执行
NSDefaultRunLoopMode 按住其它控件,会停止执行,和第一种方式一样
self.timer = [NSTimer ez_timerWithTimeInterval:1.f block:^{
    NSLog(@"nextPage"); [weakSelf nextPage]; } repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值