检测NSNumber是否为零,零或0 [英] Detect if NSNumber is zero, nil or 0
问题描述
我在核心数据中有一个变量.我要检测的情况是它为nil零,null或否则没有很好的值,例如222或333.
I have a variable in core data. I want to detect for the cases where it is nil zero, null or otherwise does not have a nice value such as 222 or 333.
这应该是微不足道的,但是我被Objective-C的语法所困扰.
This should be trivial but I am getting caught up in Objective-C's syntax.
以下代码不起作用:
if (_item.id!=nil && _item.id!=0) {
//do something
}
注释ID应该是一个NSNumber.
Of note id should be an NSNumber.
它定义为
@property (nonatomic, retain) NSNumber * id;
我应该澄清一下,当该值以0记录到控制台时,它不起作用.
I should clarify that it is not working when the value logs to console as 0.
考虑到变量类型和核心数据的工作方式,我无法告诉您是什么导致变量以"0"记录到控制台,但是某种原因导致了它这样做.基本上,我想排除值不是非零整数(用数学方法,而不是计算机科学术语)的情况.
Given the way variable types and core data work, I cannot tell you what causes the variable to log to console as '0' but something is causing it to do so. Basically, I want to exclude cases where the value is anything other than a non-zero integer (in mathematical, not computer science terms).
推荐答案
要检查存储在NSNumber
中的数值,您必须调用一种为您提供原始类型的方法.
To check the numeric value stored in an NSNumber
, you have to call one of the methods which give you a primitive type.
例如integerValue
,unsignedLongLongValue
,doubleValue
要正确检查nil
和值0
,您需要以下内容:
To correctly check for nil
and a value of 0
, you need the following:
if (_item.id != nil && [_item.id intValue] != 0) {
// code here
}
由于向nil
引用发送消息会返回0
,因此您可以使用快捷方式:
Because sending a message to a nil
reference returns 0
, you can take a shortcut:
if ([_item.id intValue] != 0) ...
之所以可行,是因为_item.id
必须为非零,才能从intValue
返回非零值.
This works because _item.id
has to be non-nil to return a non-zero value from intValue
.
这篇关于检测NSNumber是否为零,零或0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!