解决NSTimer存在的内存泄漏的问题

   创建定时器会在一定的间隔后执行某些操作,一般大家会这样创建定时器,这样创建的定时,self对定时器有个引用,定时器对self也有个引用,造成了循环引用,最终造成了内存泄漏,如果定时器在做下载的操作就会一直下载。

 self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startTimer) userInfo:nil repeats:YES];

 解决办法:首先创建NSTimer的这样的一个分类:NSTimer+eocBlockSupports代码如下,可以看出它把定时器需要执行的操作放在了block这个参数中,返回一个定时器时block传给了userInfo ,执行定时器的操作时定时器获得userinfo的block执行block

//
//  NSTimer+eocBlockSupports.h


#import <Foundation/Foundation.h>

@interface NSTimer (eocBlockSupports)
//类方法返回一个NSTimer的实例对象 +(NSTimer *)eocScheduledTimerWithTimeInterval:(NSTimeInterval)timeInterval block:(void(^)()) block repeats:(BOOL)repeat; @end // // NSTimer+eocBlockSupports.m #import "NSTimer+eocBlockSupports.h" @implementation NSTimer (eocBlockSupports) +(NSTimer *)eocScheduledTimerWithTimeInterval:(NSTimeInterval)timeInterval block:(void(^)()) block repeats:(BOOL)repeat{ return [self scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(startTimer:) userInfo:[block copy] repeats:repeat]; } //定时器所执行的方法 +(void)startTimer:(NSTimer *)timer{ void(^block)() = timer.userInfo; if (block) { block(); } } @end

 NSTimer的分类创建完成后,创建定时的代码如下:一定要弱化self否则还是无法解决循环引用的问题。

   __weak typeof(self)weakSelf = self;

    self.timer = [NSTimer eocScheduledTimerWithTimeInterval:1.0 block:^{

        [weakSelf startTimer];

    } repeats:YES];

 

转载于:https://www.cnblogs.com/liyy2015/p/5632146.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值