在 Cocoa 框架中,記憶體管理透過「參考計數」(Reference Counting,亦稱「保留計數」)機制來實現。每個物件都擁有一個整數計數器,表示目前有多少「擁有者」正在使用該物件。計數器的運作規則如下:
retain 訊息,計數器加 1。release 訊息,計數器減 1。dealloc 方法銷毀物件,釋放記憶體。以下透過一個 Person 類別示範 retain/release 對計數器的影響。
#import "Person.h"
@implementation Person
- (void)dealloc {
NSLog(@"person dead");
[super dealloc];
}
@end
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *tom = [[Person alloc] init];
NSLog(@"tom retainCount: %ld", [tom retainCount]); // 1
[tom retain];
NSLog(@"tom retainCount: %ld", [tom retainCount]); // 2
[tom release];
NSLog(@"tom retainCount: %ld", [tom retainCount]); // 1
[tom release]; // 計數歸零,觸發 dealloc
}
return 0;
}

透過此機制,開發者能精確掌控物件生命週期,避免記憶體洩漏與過早釋放。