为什么UIButton不需要alloc和init?
为什么UIButton不需要alloc和init调用,而只使用UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom];
。
- 以上行是否自动分配s并初始化uibutton?
- 是否有必要释放myBtn ?,因为我没有明确地使用alloc和init。
这可能是一个简单的问题,但我不知道对此的正确答案,有人可以提供帮助吗? 任何帮助表示赞赏,提前谢谢。
方法名称遵循一套规则 – 阅读此链接 ;)
基本上,以alloc
, new
, copy
或mutableCopy
开头的名称要求您调用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];
希望有所帮助!
那么buttonWithType将返回一种类型的UIButton,它是alloc
和init
。 它也是自动释放的。
你可以自己alloc
和init
一个UIButton,这将为你提供一个类型为UIButtonTypeCustom
。
buttonWithType
返回一个自动释放的对象,您不必释放该对象。 由于您没有分配,因此无需release
。
在UIButton的情况下,类级别alloc方法来自NSObject的每个UIClass对象的实现都隐藏了如果我们写的话我们也得到了alloc方法但是Apple Guy又给了一个名为buttonwithtype类级别方法的方法,他做了这样的事情。
(id)buttonWithType:(UIButtonType)buttonType { UIButton=[NSObject alloc]; code for button type specification return id; }
这就是为什么我们不需要再做分配