iOS 容易引“起循環參考”的三種情境

來源:互聯網
上載者:User

標籤:

筆者在閱讀中總結了一下,在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

【案例】:

看下面的代碼:

 

?
12345 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

 

【案例】:

 

?
123456 @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方法。

 

?
1234 -(void)stopKeepAlive{    [_keepAliveTimer invalidate];    _keepAliveTimer = nil;}

iOS 容易引“起循環參考”的三種情境

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.