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

Posted 一米王子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决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];

 

以上是关于解决NSTimer存在的内存泄漏的问题的主要内容,如果未能解决你的问题,请参考以下文章

在 NSTimer 中播放 AVAudioPlayer,没有内存泄漏?

NSTimer 泄漏内存(CFArray?)

如何使用模块化代码片段中的LeakCanary检测内存泄漏?

APP出现内存泄漏的几种情况

NSTimer解除循环引用

🔥🔥iOS中解决NSTimer循环引用问题