为什么UIButton不需要alloc和init?

时间:2011-08-09 12:57:51

标签: iphone ios xcode ipad

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

  1. 以上行是否自动分配s并初始化uibutton ??
  2. 是否有必要释放myBtn ?,因为我没有明确地使用alloc和init。
  3. 这可能是一个简单的问题,但我不知道对此的正确答案,有人可以提供帮助吗?感谢任何帮助,提前谢谢。

4 个答案:

答案 0 :(得分:4)

然后buttonWithType将为您返回一种类型的UIButton,allocinit。它也是自动释放的。

你可以{i} allocinit你自己的UIButton,这会给你一个UIButtonTypeCustom类型的UIButton。

答案 1 :(得分:2)

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

答案 2 :(得分:2)

方法名称遵循一组规则 - read this link;)

基本上,以allocnewcopymutableCopy开头的名称要求您致电release(或autorelease)。< / p>

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

例如:

// 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];

希望有所帮助!

答案 3 :(得分:1)

对于每个UIClass对象,实现是隐藏的,在UIButton的情况下,类级别alloc方法来自NSObject,如果我们编写,我们也会得到alloc方法但是Apple Guy给出了另一个名为buttonwithtype类级别方法的方法,他做了类似的事情。此

(id)buttonWithType:(UIButtonType)buttonType
{

UIButton=[NSObject alloc];

 code for button type specification

 return id;

}

这就是为什么我们不需要再做分配

相关问题