2011-08-09 69 views
4

为什么UIButton不需要分配和初始化调用,而我们只使用 UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom];为什么UIButton不需要alloc和init?

  1. 上述行是否自动分配s并初始化uibutton?
  2. 是否需要释放myBtn ?,因为我没有明确地使用alloc和init。

这可能是一个简单的问题,但我不知道这个问题的正确答案,有没有人可以帮忙?任何帮助表示赞赏,在此先感谢。

回答

2

有一组规则,该方法名称遵循 - read this link

基本上,名称以allocnewcopymutableCopy开始需要向release(或autorelease)。

任何其他返回对象的方法都会返回自动释放对象。

例如:

// You need to release these 
NSString *myString = [[NSString alloc] init]; 
NSString *nextString = [myString copy]; 
UIbutton *button = [[UIButton alloc] initWithType:UIButtonTypeCustom]; 

// You don't need to release these 
NSString *thirdString = [NSString stringWithString:@"Hello"]; 
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 

希望帮助!

+0

非常感谢你的建议deanWombourne,这真的很有帮助 – George

4

那么buttonWithType将返回一个类型的UIButton,这是你的allocinit。它也是autoreleased。

你可以als allocinit一个UIButton你自己,这会给你一个类型为UIButtonTypeCustom的UIButton。

+0

这不一定意味着自定义按钮。但是,自动释放+1。 –

2

buttonWithType返回一个自动释放的对象,您不必释放它。由于您没有alloc,因此无需release

1

对于每个UIClass对象都隐藏实现类级别的alloc方法来自NSObject在UIButton的情况下我们也得到alloc方法如果我们写了但是苹果Guy给了一个更多的方法叫做buttonwithtype class level方法,这样

(id)buttonWithType:(UIButtonType)buttonType 
{ 

UIButton=[NSObject alloc]; 

code for button type specification 

return id; 

} 

这就是为什么我们不用做页头再次

相关问题