UIButton - alloc initWithFrame:vs. buttonWithType:

ma1*_*w28 14 objective-c uibutton ios

给定(任意):

CGRect frame = CGRectMake(0.0f, 0.0f, 100.0f, 30.0f);
Run Code Online (Sandbox Code Playgroud)

以下两个代码片段之间的区别是什么?

1.

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
Run Code Online (Sandbox Code Playgroud)

2.

    UIButton *button = [[[UIButton alloc] initWithFrame:frame] autorelease];
Run Code Online (Sandbox Code Playgroud)

ma1*_*w28 16

我认为它们是等价的.哈哈!狡诈问你偷偷摸摸的小朋克!

推理

  1. -buttonWithType:返回一个自动释放的UIButton对象.

  2. +[NSObject alloc]默认标量实例变量0,所以buttonType应该是0,或UIButtonTypeCustom.

优点缺点

  1. 你可以认为它是更清晰的使用-buttonWithType:,并设置buttonType明确的,并且它的情况下,苹果的变化是更安全的UIButtonTypeCustom1替代0(这将肯定不会发生).

  2. 另一方面,您也可以认为它的使用清晰且安全-initWithFrame.此外,许多Xcode示例项目(如"TheElements"和"BubbleLevel")都使用此方法.一个优点是你可以UIButton在应用程序的主线程已经耗尽其自动释放池的运行循环之前显式释放.而且,这就是我更喜欢选项2的原因.


Tho*_*ler 7

我强烈建议使用第一种方法(+buttonWithType),因为这是指定按钮类型的唯一方法.

如果您+alloc-initWithFrame:,buttonType设置为某个标准值(不确定哪个,并且这可能在SDK的更高版本中更改)并且您之后无法更改类型,因为该buttonType属性是只读的.