2011-11-25 74 views
0

我有一個關於內存管理的問題。 例如,我有一個iPhone應用程序,它使用乘法編程創建的視圖。例如以編程方式生成的按鈕。objective-с將跟蹤我在子視圖中的視圖

UIButton *myButton=[UIButton alloc] initWithFrame:...; //etc 

然後,通常我們添加此按鈕,以子視圖陣列:

[self.view addSubview:myButton]; 

然後我們解除按鈕。

[myButton release] 

當我需要刪除這個按鈕我怎麼能跟蹤這個按鈕在子視圖數組? 我知道我可以使用標籤屬性來做到這一點,但我認爲存在另一種方式來保持與它的聯繫。

回答

0

你可以簡單地把它分配給一個實例變量:

UIButton *myButton = ...; 
[self.view addSubView:myButton]; 
myInstanceVariable = myButton; 
[myButton release]; 

你只需要小心:只要你這樣做[myInstanceVariable removeFromSuperview];它可能會立即釋放(如果你還沒有保留它)然後它會指向無效的內存。

+0

謝謝你的幫助 – Oleg

0

您可以嘗試申報某處保留UIButton*類型的財產,可以用指針值分配給您的按鈕實例:

@interface myclass 
@property (retain, nonatomic) UIButton *savedButton; 
@end 

@implementation myclass 
@synthesize savedButton; 

- (void) someMethod... 
{ 
    ... 
    UIButton *myButton=[UIButton alloc] initWithFrame:...; 
    [self.view addSubview:myButton]; 
    self.savedButton = myButton; 
    [myButton release]; 
    ... 
} 
... 
@end 
+0

謝謝您的幫助 – Oleg