UIButton - alloc initWithFrame:vs。buttonWithType: [英] UIButton - alloc initWithFrame: vs. buttonWithType:

查看:149
本文介绍了UIButton - alloc initWithFrame:vs。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!


  1. -buttonWithType:返回自动释放的UIButton 物体

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

+[NSObject alloc] defaults scalar instance variables to 0, so buttonType should be 0, or UIButtonTypeCustom.



优点&缺点



Pros & Cons


  1. 您可能会认为使用 -buttonWithType:更清楚并明确设置 buttonType ,如果Apple将 UIButtonTypeCustom 更改为 1,则更安全而不是 0 (这肯定不会发生)。

  1. 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).

关于另一方面,你也可以说它很清楚&安全到足以使用 -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:vs。buttonWithType:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆