萬盛學電腦網

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

Xcode 專案從非 ARC 遷移到 ARC 完整指南

自動遷移(僅適用小專案)

  1. 專案 Build Settings → Objective-C Automatic Reference Counting 設為 Yes
  2. 菜單 Edit → Refactor → Convert to Objective-C ARC,選擇目標文件,Xcode 自動移除 retain/release/autorelease 等手動內存管理代碼

大型專案手動遷移核心規則

1. 禁用手動內存管理關鍵字

  • 刪除/註釋所有 dealloc、retain、release、retainCount、autorelease 調用與實現
  • dealloc 僅保留非內存釋放邏輯(如通知移除、代理清空),禁止調用 [super dealloc]

2. 替換自動釋放池

// 舊
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
... 
[pool release];

// 新
@autoreleasepool {
    ...
}

3. 橋接轉換修正

編譯報錯時按 Xcode 提示插入 __bridge、__bridge_retained、__bridge_transfer。

4. ARC 語法硬性規定

  • 不可使用 retain/release/autorelease/retainCount
  • 不可重寫 dealloc 調用 [super dealloc]
  • 不可使用 NSAllocateObject/NSDeallocateObject
  • C 結構體中不可直接存對象指針(用 __unsafe_unretained 或包裝類)
  • id 與 void* 互轉必須用 __bridge 系列關鍵字
  • 不可使用 NSAutoreleasePool,改用 @autoreleasepool
  • 屬性名不能以 new 開頭(會觸發命名規約錯誤)

第三方框架處理策略

  • 源碼開源且量小:按上述規則手動轉為 ARC
  • 大型閉源框架:在 Build Phases → Compile Sources 中對該框架文件雙擊,添加編譯標誌 -fno-objc-arc 保持非 ARC 編譯,主專案仍用 ARC
  • 混合模式:框架內部用 #if __has_feature(objc_arc) 宏區分

驗證清單

  • Analyze (Shift+Cmd+B) 無內存管理警告
  • Instruments → Leaks 測試無洩漏
  • 所有單元測試通過
copyright © 萬盛學電腦網 all rights reserved