UIButton - alloc initWithFrame: vs. buttonWithType:(UIButton - alloc initWithFrame: 与 buttonWithType:)
问题描述
给定(任意):
CGRect frame = CGRectMake(0.0f, 0.0f, 100.0f, 30.0f);
以下两个代码片段有什么区别?
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!
-buttonWithType:
返回一个自动释放的UIButton
对象.
-buttonWithType:
returns an autoreleasedUIButton
object.
+[NSObject alloc]
默认标量实例变量为0
,所以buttonType
应该是0
,或 UIButtonTypeCustom
.
+[NSObject alloc]
defaults scalar instance variables to 0
, so buttonType
should be 0
, or UIButtonTypeCustom
.
优点 &缺点
您可能会争辩说,使用
-buttonWithType:
并明确设置buttonType
会更清晰,并且在 Apple 更改UIButtonTypeCustom
是1
而不是0
(这绝对不会发生).
You could argue that it's clearer to use
-buttonWithType:
and setbuttonType
explicitly and that it's safer in case Apple changesUIButtonTypeCustom
to be1
instead of0
(which will most certainly never happen).
另一方面,你也可以争辩说它很清楚 &使用 -initWithFrame
足够安全.此外,还有许多 Xcode 示例项目,例如TheElements"和BubbleLevel"使用这种方法.一个优点是您可以在应用程序主线程的运行循环耗尽其自动释放池之前显式释放 UIButton
.而且,这就是为什么我更喜欢选项 2.
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.
这篇关于UIButton - alloc initWithFrame: 与 buttonWithType:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:UIButton - alloc initWithFrame: 与 buttonWithType:


基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01