开发者

Will a UIView release its subviews in Cocoa Touch?

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:UIControlStateNorm开发者_如何学编程al];

    [[sender superview] addSubview:clone];

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


}


[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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜