在使用 delegate 協議時,如果屬性宣告寫成下面這樣,編譯會直接報錯:
@interface AppDelegate ()
{
id testdelegate;
}
@property (nonatomic, assign) id testdelegate;
@end
@implementation AppDelegate
@synthesize testdelegate;
錯誤訊息是:
Existing instance variable 'delegate' for property 'delegate' with assign attribute must be unsafe_unretained
在實例變數前面加上 __unsafe_unretained 修飾即可通過編譯:
@interface AppDelegate ()
{
__unsafe_unretained id testdelegate;
}
@property (nonatomic, assign) id testdelegate;
@end
@implementation AppDelegate
@synthesize testdelegate;
在 non-ARC 時代,delegate 屬性一律寫成 assign,因為 delegate 通常是被動持有的一方,用 retain 會造成循環引用。但 ARC 引入後,編譯器需要明確知道「這個 assign 的語意究竟是什麼」——因為 ARC 底下的 assign 對物件型別的行為,等同於 __unsafe_unretained:不會增加引用計數,但當物件被釋放後,指標不會自動清空,仍指向已釋放的記憶體。
編譯器之所以報錯,是因為它發現實例變數的宣告與屬性的記憶體管理語意沒有明確對應,要求你把「這是一個不安全的非持有引用」這件事寫清楚。
如原文所述,這種寫法主要是為了相容 iOS 4 以下的舊版本。在現代的 ARC 專案中,更好的選擇是直接使用 weak:
@property (nonatomic, weak) iddelegate;
weak 與 unsafe_unretained 的差別在於:前者在被參照物件釋放後會自動把指標設為 nil,後者不會——指標會留著一個指向已釋放記憶體的位址,後續若誤用就會 crash。既然 weak 從 iOS 5 起就已全面支援,delegate 屬性沒有理由再使用 unsafe_unretained。