您的位置:首页 > 产品设计 > UI/UE

iOS initWithFrame:frame] 与 [UIButton buttonWithType] 对比

2016-02-25 16:07 633 查看
What's the difference between the following two code snippets?

1.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = frame;


2.
UIButton *button = [[[UIButton alloc] initWithFrame:frame] autorelease];

I think they're equivalent. Haha! Trick question you sneaky little punk!

Reasoning

-buttonWithType:
returns an autoreleased
UIButton
object.
+[NSObject alloc]
defaults scalar instance variables to
0
, so
buttonType
should be
0
, or
UIButtonTypeCustom
.

Pros & Cons

You could argue that it's clearer to use
-buttonWithType:
and set
buttonType
explicitly and that it's safer in case Apple changes
UIButtonTypeCustom
to be
1
instead of
0
(which will most certainly never happen).
On the other hand, you could also argue that it's clear & safe enough to use
-initWithFrame
. Plus, many of the Xcode sample projects, such as "TheElements" & "BubbleLevel," use this approach. One advantage is that you can explicitly release the
UIButton
before the run loop for your application's main thread has drained its autorelease pool. And, that's why I prefer option 2.
I would strongly suggest using the first approach (
+buttonWithType
), because that's the only way to specify the button type.If you
+alloc
and
-initWithFrame:
, the
buttonType
is set to some standard value (not sure which, and this could change in later versions of the SDK) and you can't change the type afterwards because the
buttonType
property is read only.
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: