【问题标题】:Objective-C keep track of my view in subviews arrayObjective-C 在子视图数组中跟踪我的视图
【发布时间】:2011-11-25 13:53:49
【问题描述】:
我有一个关于内存管理的问题。
例如,我有一个 iPhone 应用程序,它使用多个以编程方式创建的视图。
例如以编程方式生成的按钮。
UIButton *myButton=[UIButton alloc] initWithFrame:...; //etc
然后,通常我们将此按钮添加到子视图数组中:
[self.view addSubview:myButton];
然后我们释放按钮。
[myButton release]
当我需要删除此按钮时,如何在子视图数组中跟踪此按钮?
我知道我可以使用标签属性来做到这一点,但我认为存在另一种保持联系的方式。
【问题讨论】:
标签:
iphone
objective-c
uiview
subview
addsubview
【解决方案1】:
您可以简单地将其分配给实例变量:
UIButton *myButton = ...;
[self.view addSubView:myButton];
myInstanceVariable = myButton;
[myButton release];
您只需要小心:一旦您执行[myInstanceVariable removeFromSuperview]; 之类的操作,它可能会立即被释放(如果您没有保留它),然后它会指向无效内存。
【解决方案2】:
您可以尝试在某处声明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