2011-03-23 65 views
1

第一次在这里提问。UIButton的子视图需要释放?

我有一个问题,我有一个UIImageView添加作为一个子视图我UIButton,这是使用buttonWithType:(这意味着我不必松开按钮吧?)声明,但我还是要释放的子视图我的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]; 
+0

欢迎来到StackOverflow!请记住标记答案是正确的,并注意提问的方式。 – Moshe 2011-03-23 03:58:33

+0

谢谢:)哎呀注意到我已经autoreleased UIImageView,所以这是正确的? – purplelilgirl 2011-03-23 04:01:02

+0

是的,看我的答案。 – Moshe 2011-03-23 04:05:06

回答

0

答案很简单:

您的代码似乎罚款。基本的经验法则是每alloc,new,retaincopy,您需要releaseautorelease


龙答:

让我们通过线的代码行。

UIImage *circleImage = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"item-circle" ofType: @"png"]]; 

该第一行使用了一种方便的方法。因为您没有拨打allocnewretaincopy,您不需要拨打任何电话。

UIImageView *circleImageView = [[[UIImageView alloc] initWithImage: circleImage] autorelease]; 

在第二行,你叫alloc,但你打电话autoerelease,所以你是好那里。

[imageView setFrame: CGRectMake(-5, -5, 65, 65)]; 

同样,没有allocnewretain,或copy

UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom]; 

再次,您已经使用了一种方便的方法。

[button addSubview: circleImageView]; 

你还不给allocnewretain,或copy。因此,您不要拨打releaseautorelease

+0

谢谢你的澄清:)非常感谢:) – purplelilgirl 2011-03-23 04:18:35

0

作为一般规则,您自己需要发布的任何东西allocretain。但是你在这里(实质上)通过调用autorelease来做到这一点。如果你问是否需要再次发布子视图,答案是否定的。

这同样适用于您的按钮。您还没有拨打allocretain(而不是您使用的buttonWithType),因此您无需拨打release就可以了。

+0

谢谢你的回应:) – purplelilgirl 2011-03-23 04:20:02