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

查看:225
本文介绍了ObjectiveC:if(obj){...}和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为true,而1为false),并且如果指针没有指向任何东西,它都设置为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) {

因为您不需要创建中间布尔值(通过评估比较表达式).对于不确定的非零值,我不确定您指的是哪种其他语言";我能想到的最接近的事情是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必须类型定义为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){...}和if(obj!= nil){...},哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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