2011-05-03 27 views
-1

我正在開發iPad遊戲。我遇到這件事。這是我的示例代碼:@property,@synthesize並釋放Objective-C中的對象

方法1:

Foo.h 

@interface Foo : UIView{ 
    UILabel *title; 
    .... // Other objects like UISlider, UIbuttons, etc. 
} 

// I add @property for all the objects. 
@property (nonatomic, retain) UILabel *title; 

... blablabla 

Foo.m 
// I synthesize all the properties. 
@synthesize title; 
... blablabla 

// Release in dealloc method 
[title release]; 
.... 
[super dealloc]; 

方法2:

Foo.h 

@interface Foo : UIView{ 
    UILabel *title; 
    .... // Others object like UISlider, UIbuttons, etc. 
} 
// But this time I didn't add @property, synthesize and release. 

Foo.m 
// When I need the label, I allocate it: 
title = [[UILabel alloc] initWithRect: CGRect(10, 10, 100, 30)]; 
title.text = @"test"; 
[self addSubview: title]; 
[title release]; 

兩個方法1和2的工作,但什麼是兩種方法之間的差異(方法2具有更少的代碼)?

我應該使用哪種方法,爲什麼?

它與內存管理有關嗎?

+1

重複:[1](http://stackoverflow.com/questions/2032826/)[3](http://stackoverflow.com/questions/5140782/)[3](http://stackoverflow.com/questions/3169822 /)[4](http://stackoverflow.com/questions/4700296/)[5](http://stackoverflow.com/questions/3394206/)[&c。](http:// stackoverflow .com/search?page = 2&tab = relevance&q = synthesize%20iphone)當你發佈信息時,這些都會出現在「相關問題」中。發帖前請先搜索。 – 2011-05-03 20:02:31

回答

0

方法2在技術上是不正確的,因爲通過發送-release來標題,表明您不再對它感興趣。你應該使它成爲零,或者更好的是,使它成爲一個局部變量。

方法1是絕對精細,並具有中,-dealloc外部提供你總是使用屬性引用它的優勢,你不必擔心會-retain-release - 右。

+0

我想,從現在開始,我應該堅持方法1?而且,這兩種方法是否都有內存泄漏? – 2011-05-03 15:51:20

+0

@ detective-c:正如你所編寫的,你在任何一個片段中都沒有內存泄漏。方法2確實有可能將消息發送到解除分配的對象,儘管因爲您在釋放它之後沒有將實例變量設置爲零。 – JeremyP 2011-05-03 16:03:17

+0

謝謝JeremyP,我會堅持方法1然後:) – 2011-05-03 16:10:28

0

區別在於,在方法2中,您將無法訪問Foo對象外部的標題。實例變量對於類是私有的。

此外,您需要確保您平衡alloc/retain和release。