簡體   English   中英

Objective-C在子視圖數組中跟蹤我的視圖

[英]Objective-C keep track of my view in subviews array

我有一個關於內存管理的問題。 例如,我有一個iPhone應用程序,它使用以編程方式創建的多個視圖。 例如以編程方式生成的按鈕。

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

然后,通常我們將此按鈕添加到subviews數組中:

    [self.view addSubview:myButton];

然后我們釋放按鈕。

    [myButton release]

當我需要刪除此按鈕時,如何在子視圖數組中跟蹤該按鈕? 我知道我可以使用標簽屬性來做到這一點,但我認為存在另一種保持聯系的方式。

您可以簡單地將其分配給實例變量:

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

您只需要小心:只要執行[myInstanceVariable removeFromSuperview]; 它可能會立即被釋放(如果您尚未保留),然后它將指向無效的內存。

您可以嘗試在某處聲明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

暫無
暫無

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

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