Objective-C 採用手動引用計數:
alloc/new/copy/mutableCopy) → 引用計數 +1,調用者擁有對象retain → 計數 +1,獲取所有權release → 計數 -1,釋放所有權;計數歸零 → dealloc 銷毀對象autorelease → 延遲釋放,放入當前 NSAutoreleasePool,RunLoop 結束時統一 drainstringWithString:)返回 autoreleased 對象,無需 release// 循環中創建大量臨時對象 → 必須自建池防止內存峰值
for (int i = 0; i < 10000; i++) {
@autoreleasepool {
NSString *tmp = [NSString stringWithFormat:@"Item %d", i];
[self processItem:tmp];
}
}
// 非主線程必須自建池
dispatch_async(queue, ^{
@autoreleasepool {
// 後台任務代碼
}
});
retain;移除/銷毀容器 → releaseaddSubview: → retain 子視圖;removeFromSuperview → releasepushViewController: → retain;pop → release__weak/__block 打破循環// 經典循環:Parent → Child(strong),Child → Parent(delegate, strong)
@interface Parent : NSObject
@property (strong) Child *child;
@end
@interface Child : NSObject
@property (strong) Parent *delegate; // 錯誤!應為 weak/assign
@end
檢測手段:Instruments → Leaks / Allocations / Graph;靜態分析:⇧⌘B Analyze。
解決模式:
weak / __weak__weak typeof(self) weakSelf = self; 在 block 中使用| MRC 手動 | ARC 自動 |
|---|---|
| 手寫 retain/release/autorelease | 編譯器插入,不可手動調用 |
| 需實現 dealloc 釋放 ivar | 自動釋放 strong ivar,僅需釋放非 OC 資源 |
| @property(retain/assign/copy) | strong/weak/copy(推薦) |
| 易漏、易過釋、崩潰難查 | 消除 90% 內存錯誤,性能更優(編譯期優化) |
__weak typeof(self) ws = self; 在 block 內用 wsinvalidate 或弱引用代理包裝器@property (weak) id delegate;CFRetain/CFRelease 手動管理,ARC 不管malloc_history 定位釋放後使用