專案啟用 ARC,嘗試在疑似洩漏程式碼加 autorelease、將 self 改為 weakSelf,但洩漏依舊存在。
autorelease 無效,甚至可能延長物件壽命。self 都需弱引用,僅在 Block/閉包捕獲 self 形成保留循環時才需 __weak。delegate、target-action、NotificationCenter 觀察者未在 dealloc 移除,是洩漏高發區。Product > Analyze,編譯器會標記潛在洩漏模式。// Block 內捕獲 self
__weak typeof(self) weakSelf = self;
dispatch_block_t block = ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (strongSelf) {
[strongSelf doSomething];
}
};
// 移除通知觀察者
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
// 取消網路請求、計時器等
}
詳細進階技巧請參考:iOS ARC 記憶體洩漏深度解析
工具輔助 + 理解引用計數機制,是解決 ARC 洩漏的關鍵。