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
,直到松开按钮,但您不必担心任何问题,因为您分配的唯一对象已标记为自动释放。感谢您的澄清:)非常感谢:)感谢您的回复:)