简体   繁体   English

为什么UIButton不需要alloc和init?

[英]Why UIButton does not require to alloc and init?

Why UIButton does not require to alloc and init call instead we use only UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 为什么UIButton不需要alloc和init调用,而只使用UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom]; .

  1. Does the above line automatically alloc s and init the uibutton?? 以上行是否自动分配s并初始化uibutton?
  2. Is it necessary to release myBtn?,since i'm not using alloc and init explicitly. 是否有必要释放myBtn ?,因为我没有明确地使用alloc和init。

This may be a simple question but i don't know the correct answer for this, does anybody can help? 这可能是一个简单的问题,但我不知道对此的正确答案,有人可以提供帮助吗? Any help is appreciated,thanks in advance. 任何帮助表示赞赏,提前谢谢。

Well the buttonWithType will return a type of UIButton which is alloc and init for you. 那么buttonWithType将返回一种类型的UIButton,它是allocinit It is also autoreleased. 它也是自动释放的。

You can als alloc and init a UIButton your self, this will give you an UIButton of type UIButtonTypeCustom . 你可以自己allocinit一个UIButton,这将为你提供一个类型为UIButtonTypeCustom

buttonWithType returns an auto-released object, which you don't have to release. buttonWithType返回一个自动释放的对象,您不必释放该对象。 As you did not alloc , no need to release . 由于您没有alloc ,没有必要release

There's a set of rules that the method names follow - read this link ;) 方法名称遵循一套规则 - 阅读此链接 ;)

Basically, names beginning with alloc , new , copy or mutableCopy require you to call release (or autorelease ). 基本上,以allocnewcopymutableCopy开头的名称要求您调用release (或autorelease )。

Any other methods that return an object will return autoreleased objects. 返回对象的任何其他方法都将返回自动释放的对象。

For example : 例如 :

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

Hope that helps! 希望有所帮助!

The implementation is Hidden for every UIClass objects the class level alloc method comes from NSObject in case of UIButton also we get the alloc method if we write But apple Guy has given one more method called buttonwithtype class level method where he does something like this 在UIButton的情况下,类级别alloc方法来自NSObject的每个UIClass对象的实现都是隐藏的,如果我们写的话我们也得到了alloc方法但是Apple Guy还给了一个名为buttonwithtype类级别方法的方法,他做了这样的事情。

(id)buttonWithType:(UIButtonType)buttonType
{

UIButton=[NSObject alloc];

 code for button type specification

 return id;

}

thats why we need not do alloc again 这就是为什么我们不需要再做分配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM