iOS 採用參考計數(Reference Counting)管理記憶體。物件建立時計數為 1,retain +1,release -1,歸零時釋放。ARC 編譯期自動插入這些呼叫,但理解底層原理對排查洩漏至關重要。
alloc/new/copy/mutableCopy 建立 → 你擁有,需釋放。retain。autorelease 將物件加入當前池,池排空時統一 release。主執行緒 RunLoop 每圈自動排空。子執行緒需手動建立:
for _ in 0..<10 {
autoreleasepool {
let str = NSString(string: "hello world")
process(str)
} // 此處釋放
}
// 錯誤
- (NSMutableString *)getOutput {
return [[NSMutableString alloc] initWithString:@"output"];
}
// 正確
- (NSMutableString *)getOutput {
return [[[NSMutableString alloc] initWithString:@"output"] autorelease];
}
// 正確:先 retain 新值,再 release 舊值
- (void)setName:(NSString *)newName {
[newName retain];
[name release];
name = newName;
}
// 或使用 @property(nonatomic, retain) 自動合成
weak(ARC)或 assign(MRC)。self 使用 __weak typeof(self) weakSelf = self;。dealloc 釋放屬性(編譯器自動生成),但需手動清理非 OC 物件(Core Foundation、C malloc、通知觀察者等)。@property(nonatomic, copy) 適用於可變對應不可變類型(NSString、NSArray、NSDictionary、Block)。dealloc 呼叫可能觸發副作用的方法。內建記憶體管理思維,從「擁有權」角度思考每個變數生命週期,是寫出無洩漏 App 的關鍵。