设置为 nil 和 0 的变量之间的区别
if (myFloat == nil){
\\Do Method
}
在上述情况下,仅当 myFloat
为 nil
时该方法才会运行。如果 myFloat
设置为 0
,它也会运行吗?
if (myFloat == nil){
\\Do Method
}
In the above situation, the method will run only if myFloat
is nil
. Will it also run if myFloat
was set to 0
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
nil 只能与指针一起使用。它表示指针尚未设置值。
浮点数和其他 C 类型只是有一个值。 (严格意义上的浮点型和双精度型可能具有像 NaN 这样的值,但这更难管理)
在 Objective C 中,您可以将浮点型包装在 NSNumber 类中。此类的对象由指针引用,因此 NSNumber* 类型的变量可以为 nil。
nil should only be used with pointers. It says that the pointer has not been set to a value.
Floats and other C types just have a value. (Strictly floats and double possibly can have values like NaN but this is more difficult to manage)
In Objective C you can wrap a float in the class NSNumber. An object of this class is referenced by a pointer so a variable of type NSNumber* can be nil.
嗯,从技术上讲,nil 是 0。但是,这在一定程度上取决于变量 myFloat 的类型。如果 myFloat 是 C 浮点数,则不能依赖它恰好为 0。您确实应该在 id 类型上使用 nil。
Well, nil is technically 0. However, some of this depends on what type of variable myFloat is. If myFloat is a C float, you can't depend on it being exactly 0. You really should be using nil on id types.
在回答之前,请参阅NSHipster 的此表,以回顾一下 null 系列的含义-like 符号:
NULL
(void *)0
nil
(id)0
(id)0 code>Nil
(Class)0
NSNull
[NSNull null]
如上面的值列所示,除了
NSNull
之外的所有对象都将 0 作为其基础值。我运行了一些与零检查和零检查相关的测试用例。
关键:
Before I get into my answer, see this table from NSHipster for a refresher on the meanings of the family of null-like symbols:
NULL
(void *)0
nil
(id)0
Nil
(Class)0
NSNull
[NSNull null]
As the value column above shows, all but
NSNull
have 0 as their underlying value.I ran a few test cases related to nil-checking and zero-checking.
Key: