您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

ARC 與 MRC 學習筆記:混用、洩漏與遷移規則

編輯:iOS 開發綜合

ARC 大幅簡化了記憶體管理,但它並非萬能,混用場景與循環引用仍然需要自己留意。以下把幾個容易出錯的地方整理出來。

一、Core Foundation 與 Objective-C 物件互轉

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 相容

ARC 在 iOS 4 環境下沒有 __weak 關鍵字,需以 __unsafe_unretained 代替。兩者差別在於 weak 會在物件釋放後自動變 nil,而 unsafe_unretained 會留下空指標,存取時可能崩潰。

三、ARC 下仍然會洩漏:循環強引用

ARC 並不代表不會洩漏,最常見的成因就是循環強引用。容易出問題的場合有四類:

① Outlet 型別的指標

Outlet 應宣告為 weak,避免 view 持有 controller、controller 又持有 view 的循環。

② delegate

delegate 屬性一定要設為 weak,理由同上。

③ block

下面這段在 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。

四、@autoreleasepool 取代 NSAutoreleasePool

ARC 不支援 NSAutoreleasePool,改用 @autoreleasepool。它同時適用於 ARC 與非 ARC 環境,而且效率更好,Apple 的說法是:

ARC provides @autoreleasepool blocks instead. These have an advantage of being more efficient than NSAutoreleasePool.

五、使用 ARC 必須遵守的新規則

  • 不要在 dealloc 中呼叫 [super dealloc]。
  • 不可使用 retain / release / retainCount / autorelease。
  • 不可使用 NSAllocateObject / NSDeallocateObject。
  • 不可使用 NSZone。
  • Objective-C 物件不能作為 C 結構體(struct / union)的成員。

最後一點補充:在 MRC 與 ARC 混編的專案裡,可以用 -fobjc-arc 與 -fno-objc-arc 編譯旗標逐檔案指定,這在逐步遷移老專案時比一次全改安全得多。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved