Objective c UIButton的子视图是否需要释放?

Objective c UIButton的子视图是否需要释放?,objective-c,uibutton,release,subview,autorelease,Objective C,Uibutton,Release,Subview,Autorelease,第一次在这里问问题 我有一个问题,我有一个UIImageView作为子视图添加到我的UIButton,它是使用按钮声明的,它的类型为:(这意味着我不必右键释放按钮),但我仍然必须释放UIButton的子视图吗 代码位: UIImage *circleImage = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"item-circle" ofType: @"png"]]; UIImageVie

第一次在这里问问题

我有一个问题,我有一个
UIImageView
作为子视图添加到我的
UIButton
,它是使用
按钮声明的,它的类型为:
(这意味着我不必右键释放按钮),但我仍然必须释放
UIButton
的子视图吗

代码位:

UIImage *circleImage = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"item-circle" ofType: @"png"]];
UIImageView *circleImageView = [[[UIImageView alloc] initWithImage: circleImage] autorelease];
[imageView setFrame: CGRectMake(-5, -5, 65, 65)];

UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
[button addSubview: circleImageView];

简短回答:

你的代码看起来不错。基本的经验法则是,对于每个
alloc
new
retain
、或
copy
,您都需要
发布
自动释放


长答案:

让我们逐行检查您的代码

UIImage *circleImage = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle]  pathForResource: @"item-circle" ofType: @"png"]];
第一行使用了一种方便的方法。您不需要对任何内容调用release,因为您没有调用
alloc
new
retain
copy

UIImageView *circleImageView = [[[UIImageView alloc] initWithImage: circleImage] autorelease];
UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
在第二行中,您调用
alloc
,然后调用
autoererelease
,因此您在这方面做得很好

[imageView setFrame: CGRectMake(-5, -5, 65, 65)];
同样,无
alloc
new
retain
copy

UIImageView *circleImageView = [[[UIImageView alloc] initWithImage: circleImage] autorelease];
UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
再一次,您使用了一种方便的方法

[button addSubview: circleImageView];

您仍然没有调用
alloc
new
retain
copy
。因此,一般情况下,您不需要调用
release
autorelease

,任何
alloc
retain
您自己需要释放的内容。但在这里(本质上)通过调用
autorelease
实现了这一点。如果您询问是否需要再次释放子视图,答案是否


这同样适用于您的按钮。您没有调用
alloc
retain
(而是使用了类型为
按钮),因此您不需要在其上调用
release

欢迎使用StackOverflow!记住将答案标记为正确,并注意提问的方式。谢谢:)Oops注意到我已经自动删除了UIImageView,这样就可以正常工作了?您的代码很好,
按钮将保留
circleImageView
,直到松开按钮,但您不必担心任何问题,因为您分配的唯一对象已标记为自动释放。感谢您的澄清:)非常感谢:)感谢您的回复:)