iOS initWithFrame:frame] 与 [UIButton buttonWithType] 对比
2016-02-25 16:07
633 查看
What's the difference between the following two code snippets?
1.
2.
I think they're equivalent. Haha! Trick question you sneaky little punk!
On the other hand, you could also argue that it's clear & safe enough to use
I would strongly suggest using the first approach (
[/code]
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
UIButtonobject.
+[NSObject alloc]defaults scalar instance variables to
0, so
buttonTypeshould be
0, or
UIButtonTypeCustom.
Pros & Cons
You could argue that it's clearer to use-buttonWithType:and set
buttonTypeexplicitly and that it's safer in case Apple changes
UIButtonTypeCustomto be
1instead 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
UIButtonbefore 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
+allocand
-initWithFrame:, the
buttonTypeis 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
buttonTypeproperty is read only.
[/code]
相关文章推荐
- CodeForces 626 A. Robot Sequence(水~)
- Android uiautomator环境搭建
- angular 服务(factory service constant value provider)学习笔记
- Divide and Conquer
- 1101 Quick Sort
- UIImageView用法
- 浅谈 easyui tabs 的href和content属性
- java request获取各种数据
- incredibuild 命令行 error D8037
- 用数据库连接池解决org.hibernate.exception.JDBCConnectionException:could not execute query
- Ultra-QuickSort(树状数组求逆序对数)
- IOS之UITabBarController
- 基于pt-query-digest的慢查询日志持续追踪 推荐
- 从源代码安装Guidance
- ./configure: error: the GeoIP module requires the GeoIP library.
- 《iOS Human Interface Guidelines》——The Status Bar
- UIResponder
- Formal System-相继式演算(Sequenz)
- iOS开发系列--UITableView全面解析
- queue