開啟 ARC 之後,內存由系統自動管理,但只要項目裡出現 block,就要格外小心循環引用帶來的洩露。這幾天就踩了一個坑:頁面正常 dismiss 之後,dealloc 遲遲不被調用,查了很久才定位到原因。
- (void)getMyrelatedShops
{
[self.loadTimer invalidate];
self.loadTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:discoverView
selector:@selector(loadWaiting)
userInfo:nil
repeats:YES];
sendedRequest = [[FindShopService sharedInstance] getMyRelatedShopsWithPageNO:pageNo
successBlock:^(TMRequest *request) {
[self.loadTimer invalidate];
[self shopListRequestFinished:request];
} failedBlock:^(TMRequest *failedRequest) {
[self.loadTimer invalidate];
[self shopListRequestFailed:failedRequest];
}];
}
表面上沒什麼問題,細看卻有兩處致命傷:
三者構成閉環:self → sendedRequest → block → self,引用計數永遠無法歸零,dealloc 自然不會被調用。
只要重複型 timer 沒有被 invalidate,它的 target 就會被一直持有而不釋放。這意味著:如果你把 self 作為 target,就不可能在 dealloc 裡 invalidate 這個 timer——因為 timer 沒失效,dealloc 永遠不會被執行,形成死鎖式的循環。因此必須在別的時機(如 viewDidDisappear、頁面退出入口)主動 invalidate,而不是指望 dealloc。
- (void)getMyrelatedShops
{
[self.loadTimer invalidate];
self.loadTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:discoverView
selector:@selector(loadWaiting)
userInfo:nil
repeats:YES];
// 用弱引用打破 block 對 self 的持有
__unsafe_unretained FindShopVC *wfindShopVC = self;
sendedRequest = [[FindShopService sharedInstance] getMyRelatedShopsWithPageNO:pageNo
successBlock:^(TMRequest *request) {
[wfindShopVC.loadTimer invalidate];
[wfindShopVC shopListRequestFinished:request];
} failedBlock:^(TMRequest *failedRequest) {
[wfindShopVC.loadTimer invalidate];
[wfindShopVC shopListRequestFailed:failedRequest];
}];
}
這樣就打破了循環引用,頁面注銷時 dealloc 能正常執行。
示例中的 __unsafe_unretained 不設置弱引用標記,運行時不會自動置 nil,若對象已釋放再訪問就是野指針。更安全的是 __weak:
__weak typeof(self) weakSelf = self;
sendedRequest = [[FindShopService sharedInstance] getMyRelatedShopsWithPageNO:pageNo
successBlock:^(TMRequest *request) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
[strongSelf.loadTimer invalidate];
[strongSelf shopListRequestFinished:request];
} failedBlock:^(TMRequest *failedRequest) {
// 同上處理
}];
至於 timer,iOS 10 之後可以使用 block 版本的 scheduledTimerWithTimeInterval:repeats:block:,徹底告別 target-action 造成的持有問題。排查這類洩露時,Xcode 的 Instruments → Leaks 與 Memory Graph Debugger 能直接畫出引用環,比肉眼推斷快得多。