iOS:如何检查“int”值是否等于“nil”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7160143/
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-08-30 21:13:17  来源:igfitidea点击:

iOS: How to Check if an "int" Value Equals to "nil"

iosif-statementintnull

提问by Ohad Regev

I have an int value defined in one of my method:

我在我的方法之一中定义了一个 int 值:

int value = [self someMethodThatGetsAnINT];

int value = [self someMethodThatGetsAnINT];

Later on I have some "ifs" that check upon this value.

后来我有一些“ifs”来检查这个值。

How to I express: if (value == nil)?

我如何表达:if (value == nil)

When I try do this intuitive code writing I get a warning saying:

当我尝试编写这种直观的代码时,我收到一条警告:

Semantic Issue: Comparison between pointer and integer ('int' and 'void *')

语义问题:指针和整数之间的比较('int' 和 'void *')

回答by deanWombourne

nilis just a 0:) Try this :

nil只是一个0:) 试试这个:

if (0 == value)

However, why would you be testing nilagainst an int - something sounds funny here :)

但是,为什么要nil针对 int进行测试- 这里听起来很有趣:)

回答by Tim Dean

If you really want a nil value returned, you should probably be using NSNumber as your return type instead of int. NSNumber is an class that wraps scalar values in objective-c. You can put an integer in it when you have a valid return value, or return nil when you don't.

如果你真的想要返回一个 nil 值,你可能应该使用 NSNumber 作为你的返回类型而不是 int。NSNumber 是一个在objective-c 中包装标量值的类。当你有一个有效的返回值时,你可以在其中放入一个整数,或者当你没有时返回 nil。

回答by smitec

you can probably use if (value == (int)nil)but really a function that returns an int shouldn't return nil as nil is not an integer (although it may be represented similarly).

您可能可以使用if (value == (int)nil)但实际上返回 int 的函数不应该返回 nil 因为 nil 不是整数(尽管它可能以类似的方式表示)。

thismay help clear it up a little

可能有助于澄清一点