问题描述
我正在检查iPhone应用程序 -
I'm doing a check in an iPhone application -
int var;
if (var != nil)
它有效,但在X-Code中这是生成警告指针和整数之间的比较。我如何解决它?
It works, but in X-Code this is generating a warning "comparison between pointer and integer." How do I fix it?
我来自Java世界,在那里我很确定上述陈述会因为赞美而失败。
I come from the Java world, where I'm pretty sure the above statement would fail on compliation.
推荐答案
原语不能 nil
。 nil
保留用于指向Objective-C对象的指针。 nil
在技术上是指针类型,混合指针和整数将没有强制转换将几乎总是导致编译器警告,但有一个例外:完全可以隐式转换整数0到没有强制转换的指针。
Primitives can't be nil
. nil
is reserved for pointers to Objective-C objects. nil
is 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.
如果要区分0和无值,请使用 class:
If you want to distinguish between 0 and "no value", use the NSNumber
class:
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
这篇关于如何测试Objective-C中的基元是否为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!