2014-09-23 80 views
-1
@interface Rectangle 
@property (retain) UIView *view; 
@end 

@implementation Rectangle 

CGRect frame = CGMakeRect(); 
self.view = [[UIView alloc] initWithFrame:frame] 
Student *student=[[Student alloc]init]; 
[student release];       // not using this but using dealloc on it see below 
  • (void)dealloc {_view release; [super dealloc]; [學生dealloc]; } @end

我的問題是: 這裏我們爲什麼要解除超對象的內存????如果我們釋放釋放它的學生的記憶會發生什麼?我必須手動釋放聲明爲保留的屬性嗎?

+0

問自己爲什麼不使用ARC(自動參考計數)。 – rmaddy 2014-09-23 18:33:23

+0

並找到一個現代化的教程。 '@ synthesize'行不需要。 – rmaddy 2014-09-23 18:34:10

+1

半無關,但如果你沒有使用ARC,並且像你在那裏重寫-dealloc那樣,你必須在它的末尾調用[super dealloc]。否則,你會泄漏物體。 – 2014-09-23 18:40:34

回答

1

retaindealloc不恭維。 retainrelease是補充,分別添加到對象的引用計數和從中減去。

如果你的合成二傳手是retain,那麼你的dealloc應該做release(和[super dealloc])。

現代的方法是使用ARC,降@synthesize,始終參閱您的屬性與合成的getter和setter方法,就像這樣:

id foo = self.property; 
self.property = foo; 

init,它是更好地說:

_property = foo; 
+0

就像說學生*學生= [[Student alloc] init];然後[學生髮布];它並像上面那樣使用dealloc然後[super dealloc] dealloc方法釋放哪個對象?以及爲什麼我們必須釋放超級對象? – 2014-09-23 20:48:32

+0

Dealloc是一個令人困惑的名字。它不會釋放對象,它會警告對象將釋放它,使對象有機會釋放其保留的任何對象。調用super dealloc調用繼承的dealloc,它將釋放由超類定義的屬性。 – danh 2014-09-23 20:58:47

+0

這是一個關於這個主題的好文檔,是在ARC推出之後編寫的。現代化的方法是使用ARC,這可以簡化很多。但是,您正在學習舊方法,因爲它會幫助您更好地理解ARC。 http://rypress.com/tutorials/objective-c/memory-management.html – danh 2014-09-23 21:00:52

相關問題