ARC 大幅簡化了記憶體管理,但它並非萬能,混用場景與循環引用仍然需要自己留意。以下把幾個容易出錯的地方整理出來。
CF 物件不受 ARC 管理,兩者互轉時必須明確宣告所有權該由誰接手。三個橋接關鍵字:
(1)__bridge_transfer(或 CFBridgingRelease):把所有權從 CF 交給 ARC,同時消耗掉一個 retain count。
id someObj = (__bridge_transfer NSString *)op; // 等效於: // id someObj = (__bridge NSString *)op; // CFRelease(op);
(2)__bridge_retained(或 CFBridgingRetain):把物件交給 CF 端並保留 +1 的 retain count,後續必須像處理 CFStringCreateCopy() 的結果一樣自行 CFRelease。
CFTypeRef someTypeRef = (__bridge_retained CFTypeRef)op; // 等效於: // CFRetain((__bridge CFTypeRef)op); // CFTypeRef someTypeRef = (__bridge CFTypeRef)op;
(3)__bridge:單純轉型,不轉移所有權。若不確定該用哪一個,就用這個,它不會造成洩漏也不會造成提前釋放。
ARC 在 iOS 4 環境下沒有 __weak 關鍵字,需以 __unsafe_unretained 代替。兩者差別在於 weak 會在物件釋放後自動變 nil,而 unsafe_unretained 會留下空指標,存取時可能崩潰。
ARC 並不代表不會洩漏,最常見的成因就是循環強引用。容易出問題的場合有四類:
Outlet 應宣告為 weak,避免 view 持有 controller、controller 又持有 view 的循環。
delegate 屬性一定要設為 weak,理由同上。
下面這段在 MRC 下完全正常:
MyViewController * __block myController = [[MyViewController alloc] init…];
myController.completionHandler = ^(NSInteger result) {
[myController dismissViewControllerAnimated:YES completion:nil];
};
但在 ARC 下會洩漏,myController 指向的物件永遠無法釋放。原因是:__block 修飾的變數被 block 捕獲時,MRC 不會增加引用計數,而 ARC 會加一。
三種解法:
方案一:用完設 nil
myController.completionHandler = ^(NSInteger result) {
[myController dismissViewControllerAnimated:YES completion:nil];
myController = nil; // 斷開循環
};
方案二:block 內改用 weak 指標
MyViewController *myController = [[MyViewController alloc] init…];
MyViewController * __weak weakMyViewController = myController;
myController.completionHandler = ^(NSInteger result) {
[weakMyViewController dismissViewControllerAnimated:YES completion:nil];
};
這樣不會增加引用計數,但存在隱患:若外部先釋放了物件,block 內的操作就變成空轉。
方案三:weak 進、strong 出(推薦)
MyViewController *myController = [[MyViewController alloc] init…];
MyViewController * __weak weakMyController = myController;
myController.completionHandler = ^(NSInteger result) {
MyViewController *strongMyController = weakMyController;
if (strongMyController) {
[strongMyController dismissViewControllerAnimated:YES completion:nil];
}
};
block 執行時把 weak 指標轉成區域的 strong 指標,就能保證 block 執行期間物件不會被中途釋放。這是實務上最穩定的寫法。
@implementation AnimatedView {
NSTimer *timer;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
timer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(handleTimer:)
userInfo:nil
repeats:YES];
}
return self;
}
- (void)dealloc {
[timer invalidate];
}
乍看沒問題,但 dealloc 永遠不會被呼叫:self 強引用 timer,timer 又強引用 self(target),形成典型循環。解法是讓 timer 成為 weak 屬性,或改用 scheduledTimerWithTimeInterval:repeats:block: 並搭配 weak self。另外 GCD 的 dispatch_source_t 也需要確寶在 dealloc 之外的地方 cancel。
ARC 不支援 NSAutoreleasePool,改用 @autoreleasepool。它同時適用於 ARC 與非 ARC 環境,而且效率更好,Apple 的說法是:
ARC provides @autoreleasepool blocks instead. These have an advantage of being more efficient than NSAutoreleasePool.
[super dealloc]。retain / release / retainCount / autorelease。NSAllocateObject / NSDeallocateObject。最後一點補充:在 MRC 與 ARC 混編的專案裡,可以用 -fobjc-arc 與 -fno-objc-arc 編譯旗標逐檔案指定,這在逐步遷移老專案時比一次全改安全得多。