如何删除已释放的子视图

发布于 2024-11-09 15:49:53 字数 481 浏览 0 评论 0原文

初学者的问题:我试图在将子视图添加到视图然后释放它之后将其删除,即我有:

for (int i = 0; i < 9, i++) {
        UIButton *btn = [indexButtons objectAtIndex:i];
    btn.tag = x;
    [notePage1 addSubview:btn];
    [btn release];

}

如何摆脱这些 btn 之一,例如数字 0?我想到

UIButton *btn = [indexButtons objectAtIndex:0];
if ([btn isDescendantOfView:notePage1]) { [btn removeFromSuperview]; }
[btn release];

但这只会使应用程序崩溃。我根本没有收到错误日志? - 应用程序简单地终止。我该如何正确地做到这一点?

A beginner's question: I am trying to remove a subview after having added it to a view and then releasing it, i.e. I have:

for (int i = 0; i < 9, i++) {
        UIButton *btn = [indexButtons objectAtIndex:i];
    btn.tag = x;
    [notePage1 addSubview:btn];
    [btn release];

}

How can I get rid of one of these btn, e.g. number 0? I thought of

UIButton *btn = [indexButtons objectAtIndex:0];
if ([btn isDescendantOfView:notePage1]) { [btn removeFromSuperview]; }
[btn release];

But this will simply crash the app. I get no error log at all? - app simply terminates. How do I do this properly?

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

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

发布评论

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

评论(3

浪推晚风 2024-11-16 15:49:53

您不应该释放该按钮,因为您没有分配它。

这都是关于对象所有权的。你永远不应该释放一个不属于你的对象。您可以通过发送以下消息之一来获取对象的所有权:

  • alloc
  • new
  • keep
  • copy

You shouldn't release the button, because you didn't allocate it.

It's all about object ownership. You should never release an object that you don't own. You can take ownership of an object by sending one of the following messages:

  • alloc
  • new
  • retain
  • copy
蓝颜夕 2024-11-16 15:49:53

您不应该释放任何这些片段中的按钮。仅当您专门使用了 retainalloccopynew 时才使用 release >。

您的代码应该是:

for (int i = 0; i < 9, i++) {
        UIButton *btn = [indexButtons objectAtIndex:i];
    btn.tag = x;
    [notePage1 addSubview:btn];
}

添加

UIButton *btn = [indexButtons objectAtIndex:0];
if ([btn isDescendantOfView:notePage1]) { [btn removeFromSuperview]; }

到超级视图会自动增加保留计数并自动删除发布。您不必担心这些。

You shouldn't release the button in any of these snippets. You only use release if you have specifically used retain, alloc, copy or new.

Your code should be:

for (int i = 0; i < 9, i++) {
        UIButton *btn = [indexButtons objectAtIndex:i];
    btn.tag = x;
    [notePage1 addSubview:btn];
}

and

UIButton *btn = [indexButtons objectAtIndex:0];
if ([btn isDescendantOfView:notePage1]) { [btn removeFromSuperview]; }

Adding to a to a superview increases the retain count automatically and removing releases automatically. You don't have to worry about any of it.

九局 2024-11-16 15:49:53

不要释放按钮,你从未分配过它们

don't release buttons, you never Alloc'ed them

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