UIView 会在 Cocoa Touch 中释放它的子视图吗?
如果我在运行时创建一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[UIButton buttonWithType:UIButtonTypeRoundedRect]
为您提供一个已经自动释放的对象。这意味着您不“拥有”该对象,因此您没有责任释放它。
如果您要保留它,那么您将明确表示您想为自己保留该对象,这意味着您将承担释放它的责任。
UIView
将保留其子视图,因此UIView
负责释放它们。当自身被释放时,或者当子视图从超级视图中删除时,UIView
将释放其子视图。基本上,如果您没有
alloc/init
、new
、copy
或retain
对象,那么它就不是您的对象,您不负责释放它。您不必担心它,拥有该对象的任何对象(在您的情况下为 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 theUIView
's responsibility to release them. TheUIView
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
orretain
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 theUIView
) will release it when it's done with it.当您
addSubview:
时,接收者保留参数,并在您通过其中一种方法删除它时释放它。When you
addSubview:
the receiver retains the argument, and releases it when you remove it via one of the methods that does.