给定(任意):
CGRect frame = CGRectMake(0.0f, 0.0f, 100.0f, 30.0f);
下面两个代码片段有什么区别?
1.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = frame;
2.
UIButton *button = [[[UIButton alloc] initWithFrame:frame] autorelease];
最佳答案
我认为它们是等价的。哈哈!诡计多端的问题,你这个鬼鬼祟祟的小混混!
推理
-buttonWithType:
返回一个自动释放的UIButton
对象。+[NSObject alloc]
默认标量实例变量为0
,所以buttonType
应该是0
,或UIButtonTypeCustom
。
优缺点
您可能会争辩说,使用
-buttonWithType:
并显式设置buttonType
会更清晰,并且如果 Apple 更改UIButtonTypeCustom
会更安全> 为1
而不是0
(这肯定永远不会发生)。另一方面,您也可以争辩说使用
-initWithFrame
足够清晰和安全。此外,许多 Xcode 示例项目(例如“TheElements”和“BubbleLevel”)都使用这种方法。一个优点是您可以在应用程序主线程的运行循环耗尽其自动释放池之前显式释放UIButton
。而且,这就是为什么我更喜欢选项 2。
关于ios - UIButton - alloc initWithFrame : vs. buttonWithType:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6245882/