zoukankan      html  css  js  c++  java
  • 循环引用的案例

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

    【案例】:

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

    【推荐方法】:

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

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

    二、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;
    }
    1
  • 相关阅读:
    场景设计法
    判定表驱动分析方法
    错误推测法
    Ubuntu软件包管理命令全面集锦
    MySql模糊查询
    VC++ 列表控件的使用方法
    Java笔记原生数据类型【二】
    DEDECMS 关键字不能小于2个字节!
    Linux 使用yum install安装mysql登陆不上解决办法
    PHP数据学习-二维数组【3】
  • 原文地址:https://www.cnblogs.com/fantasy3588/p/5391349.html
Copyright © 2011-2022 走看看