NSTimer内存泄漏导致控制器不调用dealloc

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//
//  NSTimer+eocBlockSupports.h
 
 
#import <Foundation/Foundation.h>
 
@interface NSTimer (eocBlockSupports)<br>//类方法返回一个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/bigshow1949/p/5642496.html