• iOS 容易引“起循环引用”的三种场景


    笔者在阅读中总结了一下,在iOS平台容易引起循环引用的四个场景:

    一、parent-child相互持有、委托模式

    【案例】:

     
    @interface FTAppCenterMainViewController ()
    {
    }
     
    @property(weak,nonatomic) UITableView* myTableView;
    @end
    这里面的myTableView就使用了weak修饰符。
    1
    @property (nonatomic, weak)  id<ftactionsheetdelegate>delegate;

     

    【推荐方法】:

    child只有parent的对象为weak类型:

    1
    @property (nonatomic, weak)  id<ftactionsheetdelegate>delegate;

     

    二、block

    【案例】:

    看下面的代码:

     

    1
    2
    3
    4
    5
    typedef void (^RequestNaviCallBack)(NSInteger naviCode,NSInteger httpCode,NSError * error);
    @interface FtNaviManager : NSObject
    {
    }
    @property (nonatomic, strong)   RequestNaviCallBack naviCallBack;
    这是一个请求导航的类,类属性持有了RequestNaviCallBack,这时,如果RequestNaviCallBack再持有self,必然造成循环引用。

     

    【推荐方法】:

    如果有循环引用,编译器会提示警告。

    如果对象没有持有Block对象,那么不会产生循环引用。如果对象持有了block对象,那么在block引用self的时候这么定义:

     

    1
    __weak typeof(self) weakSelf = self;

     

    三、NSTimer

     

    【案例】:

     

    1
    2
    3
    4
    5
    6
    @interface FtKeepAlive : NSObject
    {
        NSTimer*              _keepAliveTimer; // 发送心跳timer
    }
    //实现文件
    _keepAliveTimer = [NSTimer scheduledTimerWithTimeInterval:_expired target:self selector:@selector(keepLiveStart) userInfo:nil repeats:YES];

     

    类持有了_keepAliveTimer,_keepAliveTimer又持有了self,造成循环引用。

    【推荐方法】:

    NSTimer会持有对象,所以:在删除对象之前,需要将timer的invalidate方法。

     

    1
    2
    3
    4
    -(void)stopKeepAlive{
        [_keepAliveTimer invalidate];
        _keepAliveTimer = nil;
    }
  • 相关阅读:
    【scala】定义变量和函数
    【python】self用法详解
    【Hive】自定义函数
    【Java】抽象类和接口
    Linux中的wheel用户组是什么?
    CentOS6.9切换root用户su root输入正确密码后一直提示Incorrect password,如何解决?
    CentOS7.X中使用yum安装nginx的方法
    Win10提示“因为文件共享不安全,所以你不能连接到文件共享”如何处理
    vim编辑器-多行加注释与去注释
    CentOS7.4用yum安装并配置MySQL5.7
  • 原文地址:https://www.cnblogs.com/iOS-mt/p/4320643.html
Copyright © 2020-2023  润新知