萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 內存管理精髓:引用計數、Autorelease、循環引用與 ARC 時代最佳實踐

核心機制:引用計數

Objective-C 採用手動引用計數:

  • 創建對象(alloc/new/copy/mutableCopy) → 引用計數 +1,調用者擁有對象
  • retain → 計數 +1,獲取所有權
  • release → 計數 -1,釋放所有權;計數歸零 → dealloc 銷毀對象
  • autorelease → 延遲釋放,放入當前 NSAutoreleasePool,RunLoop 結束時統一 drain

所有權規則(黃金法則)

  1. 你創建(alloc/new/copy/mutableCopy),你負責 release/autorelease
  2. 你 retain,你負責 release
  3. 非你創建/未 retain 的對象,不要 release
  4. 便利構造器(如 stringWithString:)返回 autoreleased 對象,無需 release

Autorelease Pool 實戰

// 循環中創建大量臨時對象 → 必須自建池防止內存峰值
for (int i = 0; i < 10000; i++) {
    @autoreleasepool {
        NSString *tmp = [NSString stringWithFormat:@"Item %d", i];
        [self processItem:tmp];
    }
}

// 非主線程必須自建池
dispatch_async(queue, ^{
    @autoreleasepool {
        // 後台任務代碼
    }
});

容器類與框架的所有權語義

  • NSArray/NSDictionary/NSSet:添加元素 → retain;移除/銷毀容器 → release
  • UIView:addSubview: → retain 子視圖;removeFromSuperview → release
  • UINavigationController:pushViewController: → retain;pop → release
  • Block:捕獲外部變量 → 自動 retain(ARC 下),__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。

解決模式:

  • Delegate / Block 回調 → weak / __weak
  • 父子關係 → 父 strong 子,子 weak 父
  • NSTimer / CADisplayLink → __weak typeof(self) weakSelf = self; 在 block 中使用

ARC(自動引用計數)時代的變與不變

MRC 手動ARC 自動
手寫 retain/release/autorelease編譯器插入,不可手動調用
需實現 dealloc 釋放 ivar自動釋放 strong ivar,僅需釋放非 OC 資源
@property(retain/assign/copy)strong/weak/copy(推薦)
易漏、易過釋、崩潰難查消除 90% 內存錯誤,性能更優(編譯期優化)

ARC 下仍需警惕的 5 大坑

  1. Block 循環引用:__weak typeof(self) ws = self; 在 block 內用 ws
  2. NSTimer/Target-Action 循環:Timer retain target → target 持有 Timer → 互相持有。解決:invalidate 或弱引用代理包裝器
  3. Delegate 未置弱:@property (weak) id delegate;
  4. 大循環中未用 @autoreleasepool:導致內存峰值觸發 Jetsam 殺進程
  5. Core Foundation 對象:CFRetain/CFRelease 手動管理,ARC 不管

調試神器

  • Xcode Debug Navigator → Memory:實時內存曲線
  • Instruments → Allocations/Leaks:對象分配堆棧、洩漏追蹤
  • Debug Memory Graph(⌘⇧M):可視化對象引用圖,一鍵定位循環
  • Malloc Stack Logging:malloc_history 定位釋放後使用
copyright © 萬盛學電腦網 all rights reserved