[英]Why should a self-implemented getter retain and autorelease the returned object?
[英]Why “alloc” a global variables should be autorelease
一個簡單的內存管理問題如下:
-(void)viewDidLoad
{
......
self.label = [[[UILabel alloc] initWithFrame:labelFrame] autorelease];
......
}
我認為label是一個全局變量,根據管理協議,如果使用“ alloc”創建實例,則應僅“ dealloc”它,為什么在這里“ autorelease”?
我認為標簽是一個全局變量...
不, label
是該類的屬性,包含您通過self.label
語法證明的發布代碼。 它由實例變量(無論是否明確聲明)進行備份。 label
屬性的設置器負責確保正確保留傳入的值。 分配UILabel的代碼-viewDidLoad
負責釋放它,對autorelease
的調用也是如此。
...根據管理協議,如果您使用“ alloc”創建實例,則應“取消分配”該實例...
不對 你永遠不會調用-dealloc
直接-隨時調用-release
或-autorelease
當您使用您創建一個對象來完成。 有關詳細信息,請參閱內存管理規則 。
self.label = [[[UILabel alloc] initWithFrame:labelFrame] autorelease];
與
UILabel *temp = [[UILabel alloc] initWithFrame:labelFrame];
self.label = temp;
[temp release];
就適當的內存管理而言,基本上是相同的。 可以在不同的時間正確清理內存。
我假設該標簽的屬性類似於@property(nonatomic,retain)
所以該標簽繼續存在,因為當您調用self.label
時,該標簽已被該屬性保留。
自動發布會將您的變量推入池列表中以供將來發布:
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// your code
self.label = [[[UILabel alloc] initWithFrame:labelFrame] autorelease];
// your code
[pool release];
那你就不用打電話了
[self.label release];
因為變量是自動釋放的。 並在代碼行中
[pool release];
將成功發布。
這是為了漏水
Self.label是一個屬性。
UILabel * tempLabel = [[UILabel alloc] initWithFrame:labelFrame]->保留計數為1
self.label = tempLabel->現在保留計數為2
但是您只使用self.label,因此,如果您不使用autorelease或釋放您創建的標簽,則會出現內存泄漏問題;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.