Objective-C:if(object)Vs. if(object!= nil)

时间:2021-11-11 19:56:41

Assuming object is a kind of NSObject, the following if statements are equivalent, but which style should I use?

假设对象是一种NSObject,以下if语句是等价的,但我应该使用哪种样式?

if (object) {
    // ...
}

or

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

2 个解决方案

#1


13  

As you say, they're equivalent. Thus...

如你所说,它们是等价的。从而...

which style should I use?

我应该使用哪种款式?

Whichever one you want.

无论你想要哪一个。

#2


3  

They are equivalent in the sense that they do the same thing. But I would argue that the second statement makes the code more readable. When a person reads the line, they will understand that it means "if object is not pointing to nothing."

它们在做同样事情的意义上是等价的。但我认为第二个语句使代码更具可读性。当一个人阅读该行时,他们会理解这意味着“如果对象没有指向任何东西”。

Remember Knuth's dictum: a programming language is a way to deliver instructions to a machine in a human-readable form...

记住Knuth的格言:编程语言是一种以人类可读的形式向机器发送指令的方法......

#1


13  

As you say, they're equivalent. Thus...

如你所说,它们是等价的。从而...

which style should I use?

我应该使用哪种款式?

Whichever one you want.

无论你想要哪一个。

#2


3  

They are equivalent in the sense that they do the same thing. But I would argue that the second statement makes the code more readable. When a person reads the line, they will understand that it means "if object is not pointing to nothing."

它们在做同样事情的意义上是等价的。但我认为第二个语句使代码更具可读性。当一个人阅读该行时,他们会理解这意味着“如果对象没有指向任何东西”。

Remember Knuth's dictum: a programming language is a way to deliver instructions to a machine in a human-readable form...

记住Knuth的格言:编程语言是一种以人类可读的形式向机器发送指令的方法......