在 ARC 出現之前,iOS 的記憶體管理對資深與新手一視同仁地難搞。我參與過幾個採用手動記憶體管理的專案,印象最深的是一個地圖類應用——它本身就極度吃記憶體,為了解決洩漏問題,每週都得排人值班用 Instruments 逐個功能跑一遍,而每次總能揪出不少問題。其實不分級別,誰都寫得出洩漏的程式碼:規則大家都懂,可誰能保證哪天手一抖就少了一個 release?
還好專案決定轉向 ARC。以下把整個轉換過程與中途遇到的問題記錄下來,希望能幫大家少走些彎路。
一、前言
專案規模
需要轉換的 Objective-C 檔案約 1000 個。開發工具為 Xcode 6.0.1。
轉換方式
我採用 Xcode 自帶的 ARC 轉換功能。手動轉換理論上可行,但那不在本文範疇內,而且工作量絕對足以令人崩潰。
二、轉換流程
先備份程式碼
在動這麼大規模的刀之前,務必先備份:直接在本地複製一份,或者記下變更前在版控系統上的版本號。
排除不需轉換的檔案
找出專案中仍採用手動記憶體管理的第三方庫,或某些你暫時不想動的檔案,為它們加上 -fno-objc-arc 標記。
Xcode 的自動轉換工具只處理 Objective-C 物件,也就是副檔名為 .m/.mm 的兩類檔案;純 C/C++ 的 .c/.cpp 完全不用理會。
執行檢查
Xcode 轉換工具的入口如下:

點擊 Convert to Objective-C ARC 後進入檢查環節:

這一步要挑選哪些檔案參與轉換。若前面已把不需轉換的檔案都標上 -fno-objc-arc,這裡可以直接全選。
按下 Check,Xcode 會掃出所有不符合 ARC 規則的錯誤與警告,必須把錯誤全部清乾淨,才能進入真正的轉換。
收拾錯誤與警告
檢查跑完,畫面上給出這樣的提示:

三百多個錯誤,外加一千兩百多個警告,看到都想哭。這些問題的處理方式後文會單獨說明。
執行轉換
錯誤清零後會跳出這個視窗:

大意是 Xcode 即將把專案轉為 ARC 管理記憶體,所有改動會先在一個 review 介面中預覽。轉換完成後,Target 對應的 Objective-C Automatic Reference Counting 設定會被設為 YES(右上角的警告標識就是在提醒:專案已支援 ARC,但仍有檔案尚未支援):

這時離成功已經不遠了。
點 Next 進入 review 介面,形式類似用 Xcode 提交 SVN 時的確認畫面:

這裡列出所有將被修改的檔案,並可直接對比轉換前後的差異。為求穩妥,我一個不漏地點進每個檔案掃了一眼——這也是檢查有沒有漏掉不該轉換檔案的最後機會。確認無誤後按下右下角 Save,大功告成。
三、錯誤與警告怎麼解
常見錯誤
ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

property 必須明確標註記憶體管理關鍵字,在屬性定義處補上 strong 即可。
ARC forbids explicit message send of 'release'

這種情況通常是程式碼中包了含 release 的巨集,把該巨集與所有使用處一併刪掉。
Init methods must return a type related to the receiver type

原因很樸素:A 類別裡有個以 init 開頭的方法,回傳的卻是 B 型別。乖乖改方法名吧。
Cast of C pointer type 'void *' to Objective-C pointer type 'iFlyTTSManager_old *' requires a bridged cast

這是 Toll-Free Bridging 的轉換問題,ARC 下依情境套用對應的橋接關鍵字即可,後文會專門說明。
常見警告
處理警告的目的是消除潛在隱患。既然 Xcode 都提示了,每一條都值得認真看待。
Capturing self in this block is likely to lead to a retain cycle

典型的 block 循環引用,把 block 內的 self 換成指向自己的 weak 指標即可。
Using 'initWithArray:' with a literal is redundant

原來是多余的 alloc,照 Xcode 提示刪掉就好:

Init methods must return a type related to the receiver type

同樣是 A 類別中以 init 開頭卻回傳 B 型別的問題,改方法名。
Property follows Cocoa naming convention for returning 'owned' objects

因為 @property 名稱以 new 開頭了。解法是把對應的 getter 改成非 new 開頭:

記住:ARC 下方法名若以 new/alloc/init 開頭,而它又不是類別的初始化方法,就要小心了——要麼報錯,要麼警告。
Block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior

意思是 block 裡用到了 self 的實例變數 _selectedModeMarkerView,於是 block 隱式 retain 了 self。Xcode 擔心這會造成困惑甚至循環引用,因此要求你明確寫出 self。兩種改法:一是照提示改成 self->_selectedModeMarkerView:

二是直接關掉這條警告(名稱 Implicit retain of 'self' within blocks,對應 Clang 關鍵字 -Wimplicit-retain-self):

Weak property may be unpredictably set to nil/Weak property 'delegate' is accessed multiple times in this method but may be unpredictably set to nil; assign to a strong variable to keep the object alive

這是整個專案裡數量最龐大的一類警告,原因是所有 delegate 屬性都宣告為 weak。Xcode 預設開啟了兩項相關檢查,關掉即可:

Capturing 'self' strongly in this block is likely to lead to a retain cycle

這是真真切切的 block 循環引用洩漏,當年寫下的坑。修改方案:

Method parameter of type 'NSError __autoreleasing *' with no explicit ownership

照提示補上 __autoreleasing 關鍵字即可。
以上僅列出數量較多的幾類,其餘不再逐一列舉。另外推薦 Mattt Thompson 大神整理的 Clang 警告對照網站 https://fuckingclangwarnings.com/,以後查 warning 輕鬆許多。
四、Xcode 自動做了哪些改動
關鍵字轉換
retain 自動轉為 strong:

assign 轉為 weak。修飾 Objective-C 物件或 id 型別的 assign 會被轉成 weak:

但修飾 Int/bool 等數值變數的 assign 不會轉換:

關鍵字刪除
與手動記憶體管理相關的 release/retain/autorelease/super dealloc 等會被移除。若 dealloc 除了這些語句之外還有別的程式碼,方法會保留:

否則整個方法都會被刪掉:

關鍵字替換
block 關鍵字會被自動替換為 weak:

NSAutoreleasePool 不支援 ARC,會被替換成 @autoreleasepool:

五、關於被巨集註解的程式碼
用巨集封裝的物件釋放程式碼,例如:
#define RELEASE_SAFELY(__POINTER) { \
[(__POINTER) release]; (__POINTER) = nil; \
}執行 ARC 轉換檢查時,Xcode 會在所有使用該巨集的地方報錯:

把巨集與使用處一起刪除即可。
而被巨集註解掉的程式碼,Xcode 在轉換時完全不會處理:

這點相當坑:你根本預估不到專案裡用了多少巨集、註解掉了多少程式碼。等你以為大功告成,卻在某天開啟某個巨集時迎面撞上一堆轉換不彻底的問題。這種情況沒轍,只能遇到一個改一個。
六、ARC 與 block
無論 MRC 還是 ARC,block 循環引用導致的洩漏都很惱人。MRC 下用 __block 關鍵字就能解決,ARC 下則稍微複雜些。
__block 關鍵字
block 內修改外部變數
和 MRC 一樣,ARC 下若要在 block 中修改外部定義的變數,仍需 __block 修飾:
__block NSString *name = @"foggry";
self.expireCostLabel.completionBlock = ^(){
name = @"wangzz";
};上例中 name 需要在 block 內被修改,因此必須加 __block。
__block 在 MRC 與 ARC 中的差異
ARC 下,block 會 retain 以 __block 修飾的物件;MRC 下則不會。官方文件 Transitioning to ARC Release Notes 有明確說明:
In manual reference counting mode, __block id x; has the effect of not retaining x. In ARC mode, __block id x; defaults to retaining x (just like all other values).
下面的程式碼在 MRC 與 ARC 中都存在洩漏:
MyViewController *myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler = ^(NSInteger result) {
[myController dismissViewControllerAnimated:YES completion:nil];
};MRC 下可以這樣修:
MyViewController * __block myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler = ^(NSInteger result) {
[myController dismissViewControllerAnimated:YES completion:nil];
};但在 ARC 中這麼改無效。如前所述,ARC 下 completionHandler 的 block 仍會 retain myController,洩漏照舊。ARC 有兩種解法,第一種是在 block 用完後把指標指向 nil:
MyViewController * __block myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler = ^(NSInteger result) {
[myController dismissViewControllerAnimated:YES completion:nil];
myController = nil;
};沒有 strong 指標指向該物件時,它就會被釋放。
第二種直接用 weak 取代 __block:
MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyViewController = myController;
myController.completionHandler = ^(NSInteger result) {
[weakMyViewController dismissViewControllerAnimated:YES completion:nil];
};這樣 block 根本不會 retain myController。
存在循環引用關係
若 self 直接或間接強引用 block,而 block 內又需要使用 self,兩者就形成循環引用。此時必須用 __weak 定義一個指向 self 的指標,並在 block 中使用它:
MessageListController * __weak weakSelf = self;
self.messageLogic.loadMoreBlock = ^(IcarMessage * theMessage) {
[weakSelf.tableView setPullTableIsLoadingMore:YES];
};值得說明的是,weakSelf 對 self 只是弱引用,但 self 對 block 卻是強引用,因此 self 的生命週期必定長於 block,不必擔心 block 執行時 self 已被釋放。
不存在循環引用關係
再看一個例子:
MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyController = myController;
myController.completionHandler = ^(NSInteger result) {
MyViewController *strongMyController = weakMyController;
if (strongMyController) {
// ...
[strongMyController dismissViewControllerAnimated:YES completion:nil];
// ...
}
else {
// Probably nothing...
}
};如前面所述,block 內不能直接使用 myController,否則洩漏。因此先用 weak 指標指向它,再在 block 開頭宣告一個臨時的 strong 指標 strongMyController 指向 weakMyController,實質效果就是 block 對 myController 做了強引用。當 block 執行完畢被銷毀,strongMyController 這個區域變數也跟著消失,myController 才會真正釋放。這樣就做到了:使用期間保證物件存活,用完再放棄所有權。
七、ARC 與 Toll-Free Bridging
MRC 下的 Toll-Free Bridging 不涉及記憶體管理權轉移,Objective-C(以下簡稱 OC)與 Core Foundation(以下簡稱 CF)各自管理各自的記憶體,可以直接互換使用:
NSLocale *gbNSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]; CFLocaleRef gbCFLocale = (CFLocaleRef)gbNSLocale;
ARC 下事情就複雜了。ARC 能管理 OC 物件,卻管不到 CF 物件,後者仍需手動管理。當兩者在 bridge 時,編譯器無從判斷該如何處理這個同時被 OC 與 CF 指標指向的物件,因此必須用 __bridge、__bridge_retained、__bridge_transfer 等修飾符明確告知。
__bridge
它告訴編譯器:OC 一端的引用計數仍由你(編譯器)負責,CF 一端則由開發者自行管理:
CFStringRef cfString = CFStringCreateWithCString(kCFAllocatorDefault, "CFString", kCFStringEncodingUTF8); NSString *ocString = (__bridge NSString *)cfString; CFRelease(cfString); NSLog(@"%@",ocString);
__bridge_retained 或 CFBridgingRetain
兩者作用相同,只是寫法不同。它要求 retain 物件,並由開發者在 CF 一端負責釋放。如此即使物件在 OC 端被釋放,只要你沒放掉 CF 端的引用,物件就不會真正銷毀。
NSArray *ocArray = [[NSArray alloc] initWithObjects:@"foggry", nil]; CFArrayRef cfArray = (__bridge_retained CFArrayRef)ocArray; /** 使用 cfArray **/ CFRelease(cfArray);
__bridge_transfer 或 CFBridgingRelease
同樣是兩種寫法、一個作用:bridge 的同時把物件所有權也轉移過去。
CFStringRef cfString = CFStringCreateWithCString(kCFAllocatorDefault, "CFString", kCFStringEncodingUTF8); NSString *ocString = (__bridge_transfer NSString *)cfString; //CFRelease(cfString); //不再需要釋放操作 NSLog(@"%@",ocString);
轉換時依實際需求挑選合適的關鍵字即可。另外,ARC 下 id 與 void * 也不能直接互轉,必須透過 Toll-Free Bridging 搭配適當關鍵字。
八、ARC 與 IBOutlet
IBOutlet 屬性到底該用 strong 還是 weak,一直是個疑問。官方文件的說法是:
From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File's Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create should therefore typically be weak.
翻成白話:若某個 view 是由 Controller 直接引用的頂層 view,對應的 IBOutlet 應該是 strong;若它是頂層 view 的子 view,則應為 weak,因為頂層 view 已被 Controller 強引用,而頂層 view 本身又持有這個子 view;若 Controller 需要單獨引用某個 view,或沒有引用其父 view,那也該用 strong。
實話說,如果你實在懶得分辨,把所有 IBOutlet 都設成 strong 也不會出問題——Controller 銷毀時,對應的實例變數會被釋放,strong 指標被置為 nil,同樣不會洩漏。
參考文件
Transitioning to ARC Release Notes;Managing the Lifetimes of Objects from Nib Files;Nib Memory Management。