接觸 ARC 時,我心裡一直有個誤會:以為在 ARC 下 dealloc 不會被呼叫,所以也沒必要去覆寫它。直到看到文件裡的那句話,才發現自己理解錯了。
在 ARC 環境下,覆寫的 dealloc 方法一樣會被呼叫,只是不能在實作內容中呼叫父類別的該方法。
做個簡單的測試類別 Test,建立它再銷毀它,看看 dealloc 是否真的被觸發;接著嘗試在 dealloc 最後呼叫 [super dealloc],觀察編譯器的反應。另外搭配一個視圖控制器,用兩個按鈕分別負責建立與釋放,順便驗證「引用計數歸零時是否立刻釋放」。
Test.h:
#import <Foundation/Foundation.h> @interface Test : NSObject @end
Test.m:
#import "Test.h"
@implementation Test
- (id)init {
self = [super init];
if (self) {
}
return self;
}
- (void)dealloc {
NSLog(@"dealloc");
// [super dealloc];
}
@end
視圖控制器宣告:
#import <UIKit/UIKit.h> #import "Test.h" @interface ViewController : UIViewController @property (nonatomic, strong) Test *test; @end
視圖控制器實作:
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)generateButtonPressed:(UIButton *)sender {
self.test = [[Test alloc] init];
}
- (IBAction)removeButtonPressed:(UIButton *)sender {
self.test = nil;
}
@end
一切正常。按下釋放按鈕的瞬間,Test 物件的 dealloc 立刻被呼叫,幾乎感覺不到延遲——這代表 ARC 下的引用計數回收是即時的,並不像垃圾回收那樣有等待週期。
接著把 [super dealloc] 放回 dealloc 最後一行,Xcode 5.1.1 會直接跳出提示:ARC 拒絕顯式 dealloc 訊息發送。

討論 Discussion
該物件後續收到的訊息會產生錯誤,指出訊息被送給一個已釋放的物件(前提是該記憶體尚未被重用)。
Subsequent messages to the receiver may generate an error indicating that a message was sent to a deallocated object.
你覆寫這個方法,是為了處理工件描述符這類物件實例變數以外的資源,例如:
- (void)dealloc {
free(myBigBlockOfMemory);
}
在 dealloc 的實作中,不要呼叫父類別的實作。同時也應盡量避免用 dealloc 管理檔案描述符這類有限資源的整個生命週期。
In an implementation of dealloc, do not invoke the superclass's implementation.
此外,絕對不要直接發送 dealloc 訊息。物件的 dealloc 是由 runtime 主動呼叫的,開發者不該介入這個環節。
文件寫得很明白:在未使用 ARC 時,你的 dealloc 實作必須把呼叫父類實作作為最後一行指令;反過來說,使用 ARC 時就不該出現這行。
When not using ARC, your implementation of dealloc must invoke the superclass's implementation as its last instruction.

ARC 只是幫你自動插入了 [super dealloc] 與 release 訊息,並沒有取消 dealloc 這個方法本身。因此,需要釋放非物件型別的資源(例如 malloc 出來的記憶體、CVPixelBuffer、註冊的通知觀察者)時,仍然應該覆寫 dealloc 來處理,只是別忘了不要碰 super。