为什么UIButton不需要分配和初始化调用,而我们只使用 UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom];
。为什么UIButton不需要alloc和init?
- 上述行是否自动分配s并初始化uibutton?
- 是否需要释放myBtn ?,因为我没有明确地使用alloc和init。
这可能是一个简单的问题,但我不知道这个问题的正确答案,有没有人可以帮忙?任何帮助表示赞赏,在此先感谢。
为什么UIButton不需要分配和初始化调用,而我们只使用 UIButton *myBtn = [UIButton buttonWithType:UIButtonTypeCustom];
。为什么UIButton不需要alloc和init?
这可能是一个简单的问题,但我不知道这个问题的正确答案,有没有人可以帮忙?任何帮助表示赞赏,在此先感谢。
有一组规则,该方法名称遵循 - read this link)
基本上,名称以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
。它也是autoreleased。
你可以als alloc
和init
一个UIButton你自己,这会给你一个类型为UIButtonTypeCustom
的UIButton。
这不一定意味着自定义按钮。但是,自动释放+1。 –
buttonWithType
返回一个自动释放的对象,您不必释放它。由于您没有alloc
,因此无需release
。
对于每个UIClass对象都隐藏实现类级别的alloc方法来自NSObject在UIButton的情况下我们也得到alloc方法如果我们写了但是苹果Guy给了一个更多的方法叫做buttonwithtype class level方法,这样
(id)buttonWithType:(UIButtonType)buttonType
{
UIButton=[NSObject alloc];
code for button type specification
return id;
}
这就是为什么我们不用做页头再次
非常感谢你的建议deanWombourne,这真的很有帮助 – George