簡體   English   中英

iPhone內存管理:分配和保留屬性

[英]iphone memory management: alloc and retain properties

根據文檔,您對每個分配或保留執行一次釋放(等),但是使用保留屬性又如何呢?

例如:

HEADER
@property(retain)UIView *someView;

IMPLEMENTATION
/*in some method*/
UIView *tempView = [[UIView alloc] init]; //<<<<<ALLOC - retain count = +1
[tempView setBackgroundColor:[UIColor redColor]];
self.someView = tempView; ///<<<<<RETAIN - retain count = +2
[tempView release];   ///should I do this?

或其他版本的IMPLEMENTATION

self.someView = [[UIView alloc] init]; //<<<<<ALLOC & RETAIN - retain count = +2
//now what??? [self.someView release]; ????

編輯:我沒有說清楚,但我的意思是在兩種情況下都應該做什么,而不僅僅是第一種。

/*in some method*/
UIView *tempView = [[UIView alloc] init]; //<<<<<ALLOC - retain count = +1
[tempView setBackgroundColor:[UIColor redColor]];
self.someView = tempView; ///<<<<<RETAIN - retain count = +2
[tempView release];   ///should I do this? // YES!!!!

並且,您還應該在[super dealloc]之前,在dealloc方法中釋放所有保留屬性。

您的第一個版本是正確的。 該視圖只有一個正在進行的引用,因此保留計數為1是適當的。

對於第二個示例,可以使用autorelease

self.someView = [[[UIView alloc] init] autorelease];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM