Objective-C 在子视图数组中跟踪我的视图

发布于 2024-12-17 18:43:33 字数 398 浏览 4 评论 0原文

我有一个关于内存管理的问题。 例如,我有一个 iPhone 应用程序,它使用多个以编程方式创建的视图。 例如以编程方式生成的按钮。

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

然后,通常我们将这个按钮添加到子视图数组中:

    [self.view addSubview:myButton];

然后我们释放按钮。

    [myButton release]

当我需要删除此按钮时,如何在子视图数组中跟踪此按钮? 我知道我可以使用标签属性来做到这一点,但我认为存在另一种方法来与其保持联系。

I have a question about memory management.
For example I have an iPhone application that uses multiply programmatically created views.
for example programmatically generated buttons.

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

then, normally we add this button to subviews array:

    [self.view addSubview:myButton];

then we releasing button.

    [myButton release]

When I need to remove this button how can I keep track on this button in subviews array?
I know I can do this using tag property but I think exists another way to keep connection with it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南城旧梦 2024-12-24 18:43:33

您可以简单地将它分配给实例变量:

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

您只需要小心:一旦您执行类似 [myInstanceVariable removeFromSuperview]; 的操作,它可能会立即被释放(如果您没有保留它)然后它会指向无效的内存。

You can simply assign it to an instance variable:

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

You just need to be careful: as soon as you do something like [myInstanceVariable removeFromSuperview]; it might get deallocated immediately (if you haven't retained it) and it would then point to invalid memory.

白色秋天 2024-12-24 18:43:33

您可以尝试在某处声明 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

You can try to declare somewhere a retain property of UIButton* type, that can be assigned with pointer value to your button instance:

@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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文