建立定时器会在必定的间隔后执行某些操做,通常你们会这样建立定时器,这样建立的定时,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执行blockblog
// // 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;get
self.timer = [NSTimer eocScheduledTimerWithTimeInterval:1.0 block:^{it
[weakSelf startTimer];io
} repeats:YES];class