• 解决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];

  • 相关阅读:
    Java异常面试题
    Quickhit快速击键
    多态and接口
    Java面向对象编程概述
    学生管理系统--分层开发
    类型转换
    文件上传
    ongl(示例3-6 多值类型的数据处理)
    ongl(原始类型和包装类型)
    Interceptor
  • 原文地址:https://www.cnblogs.com/liyy2015/p/5632146.html
Copyright © 2020-2023  润新知