UIView 会在 Cocoa Touch 中释放它的子视图吗?

发布于 2024-10-07 05:34:37 字数 607 浏览 0 评论 0原文

如果我在运行时创建一个 UIControl 并将其添加到视图(通过 addSubview:),视图会释放它还是我应该这样做?

这是一个示例代码:

-(IBAction) cloneMe: (id) sender{

    if (!currentY) {
        currentY = [sender frame].origin.y;
    }

    UIButton *clone = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    CGRect cloneFrame = [sender frame];
    cloneFrame.origin.y += currentY + cloneFrame.size.height + 30;
    clone.frame = cloneFrame;
    [clone setTitle:@"I'm a clone" forState:UIControlStateNormal];

    [[sender superview] addSubview:clone];

    currentY = cloneFrame.origin.y + cloneFrame.size.height;


}

If I create a UIControl at runtime and add it to a view (via addSubview:), will the view release it or am I supposed to do that?

Here's an example code:

-(IBAction) cloneMe: (id) sender{

    if (!currentY) {
        currentY = [sender frame].origin.y;
    }

    UIButton *clone = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    CGRect cloneFrame = [sender frame];
    cloneFrame.origin.y += currentY + cloneFrame.size.height + 30;
    clone.frame = cloneFrame;
    [clone setTitle:@"I'm a clone" forState:UIControlStateNormal];

    [[sender superview] addSubview:clone];

    currentY = cloneFrame.origin.y + cloneFrame.size.height;


}

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

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

发布评论

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

评论(2

青芜 2024-10-14 05:34:37

[UIButton buttonWithType:UIButtonTypeRoundedRect] 为您提供一个已经自动释放的对象。
这意味着您不“拥有”该对象,因此您没有责任释放它。

如果您要保留它,那么您将明确表示您想为自己保留该对象,这意味着您将承担释放它的责任。

UIView 将保留其子视图,因此 UIView 负责释放它们。当自身被释放时,或者当子视图从超级视图中删除时,UIView 将释放其子视图。

基本上,如果您没有 alloc/initnewcopyretain 对象,那么它就不是您的对象,您不负责释放它。您不必担心它,拥有该对象的任何对象(在您的情况下为 UIView)都会在使用完该对象后释放它。

[UIButton buttonWithType:UIButtonTypeRoundedRect] gives you an already autoreleased object.
That means you don't "own" the object and therefore you don't have the responsibility of releasing it.

If you were retaining it, then you would be explicitly saying that you want to keep this object for yourself, which means you would be taking the responsibility of releasing it.

The UIView will retain it's subviews, so it's the UIView's responsibility to release them. The UIView will release it's subviews when itself is dealloc'ed, or when the subviews are removed from the superview.

Basically, if you didn't alloc/init, new, copy or retain an object, then it's not your object and you are not responsible for releasing it. You don't have to worry about it, whatever object that owns the object (in your case the UIView) will release it when it's done with it.

煮茶煮酒煮时光 2024-10-14 05:34:37

当您 addSubview: 时,接收者保留参数,并在您通过其中一种方法删除它时释放它。

When you addSubview: the receiver retains the argument, and releases it when you remove it via one of the methods that does.

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