如何测试 Objective-C 中的原语是否为零?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/895495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:35:21  来源:igfitidea点击:

How do I test if a primitive in Objective-C is nil?

iphoneobjective-cprimitive

提问by bpapa

I'm doing a check in an iPhone application -

我正在检查 iPhone 应用程序 -

int var;
if (var != nil)

It works, but in X-Code this is generating a warning "comparison between pointer and integer." How do I fix it?

它有效,但在 X-Code 中,这会生成警告“指针和整数之间的比较”。我如何解决它?

I come from the Java world, where I'm pretty sure the above statement would fail on compliation.

我来自 Java 世界,我很确定上面的语句在编译时会失败。

回答by Adam Rosenfield

Primitives can't be nil. nilis reserved for pointers to Objective-C objects. nilis technically a pointer type, and mixing pointers and integers will without a cast will almost always result in a compiler warning, with one exception: it's perfectly ok to implicitly convert the integer 0 to a pointer without a cast.

原语不能nilnil保留用于指向 Objective-C 对象的指针。 nil从技术上讲是一种指针类型,混合指针和整数几乎总是会导致编译器警告,但有一个例外:将整数 0 隐式转换为没有强制转换的指针是完全可以的。

If you want to distinguish between 0 and "no value", use the NSNumberclass:

如果要区分 0 和“无值”,请使用NSNumber该类:

NSNumber *num = [NSNumber numberWithInt:0];
if(num == nil)  // compare against nil
    ;  // do one thing
else if([num intValue] == 0)  // compare against 0
    ;  // do another thing

回答by Frank Krueger

if (var) {
    ...
}

Welcome to the wonderful world of C. Any value not equal to the integer 0 or a null pointer is true.

欢迎来到 C 的奇妙世界。任何不等于整数 0 或空指针的值都是真的。

But you have a bug: ints cannot be null. They're value types just like in Java.

但是你有一个错误:整数不能为空。它们就像在 Java 中一样是值类型。

If you want to "box" the integer, then you need to ask it for its address:

如果你想“装箱”这个整数,那么你需要询问它的地址:

int can_never_be_null = 42; // int in Java
int *can_be_null = &can_never_be_null; // Integer in Java
*can_be_null = 0; // Integer.set or whatever
can_be_null = 0;  // This is setting "the box" to null,
                  //  NOT setting the integer value