ObjectiveC:if (obj) {...} AND if (obj != nil) {...},哪个更好? [英] ObjectiveC: if (obj) {...} AND if (obj != nil) {...}, which is better?

查看:36
本文介绍了ObjectiveC:if (obj) {...} AND if (obj != nil) {...},哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多 ObjC 代码,它们都这样做:

I've seen a lot of ObjC code which do:

obj = [[SomeObject alloc] init];
if (obj) {
/// ...
}

但据我了解,()里面的值是一个布尔值,0表示FALSE 1表示TRUE(其他语言还有另外一种情况,0为真,1为假),如果一个指针不指向对于任何东西,它都设置为 NULL(nil),即 #defined 为 0,所以我想知道如果我这样做会更好:

but as I understood it, the value inside () is a boolean, and 0 indicates FALSE 1 indicates TRUE(there is another case in other language that 0 is true and 1 is false), and if a pointer does not point to anything, it is set to NULL(nil), which is #defined to be 0, so I wonder is it better if I do:

if (obj != nil) {
/// ...
}

因为它正在检查 obj 是否为 nil,无论 nil 是什么值,所以它不依赖于 nil(或 NULL) 恰好被定义为 0?

as it IS checking if the obj is nil or not, no matter what value nil is, so it does not rely on that nil (or NULL) happen to be defined as 0?

推荐答案

经过一些测试,我确定现代编译器实际上会为这两种情况创建相同的机器代码

edit: after testing a bit, I have determined that modern compilers will actually create the same machine code for both cases;

原帖:

使用起来(可能可以忽略不计)更有效

It is (negligibly, perhaps) more efficient to use

if(obj) {

因为您不需要创建中间布尔值(通过评估比较表达式).关于非零为 FALSE,我不确定您指的是哪种其他语言";我能想到的最接近的事情是 C 程序返回 0 表示成功",而其他任何内容表示错误".我使用过的每一种现代语言都将 0 用作 FALSE,将 任何非零值用作 TRUE.

since you do not need to create the intermediary boolean value (by evaluating the comparison expression). I'm not sure which "other language" you are referring to regarding the non-zero being FALSE; the closest thing I can think of is c programs returning 0 for "success" and anything else for "error". Every modern language I have ever worked with uses 0 as FALSE and any non zero value for TRUE.

在 Objective-C 中,nil 是字面上的 0(像指针一样对待).它不仅仅是一个指向零的指针,它作为一个指针也是零.因此,它可靠地等同于 FALSE(或者,在我们的命名法中为NO").

In Objective-C, nil is literally 0 (treated like a pointer). It is not just a pointer to zero, it is zero as a pointer. It is therefore reliably equivalent to FALSE (or, in our nomenclature "NO").

编辑经过一些测试,我确定现代编译器实际上会为这两种情况创建相同的机器代码;可能是因为 nil 本质上是 typedef 为 0,所以它知道这两种检查方式都在说如果这个指针是非零的".

edit after testing a bit, I have determined that modern compilers will actually create the same machine code for both cases; probably because nil is essentiall typedef'd to 0, so it knows the two styles of checking are both saying "if this pointer is non-zero".

这篇关于ObjectiveC:if (obj) {...} AND if (obj != nil) {...},哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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