将 NSNumber 与 int 进行比较

Compare a NSNumber to an int(将 NSNumber 与 int 进行比较)
本文介绍了将 NSNumber 与 int 进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题(我认为):我正在尝试将 NSNumber 与 int 进行比较,看看它是 0 还是 1.代码如下:

I've a simple question (I think): I'm trying to compare a NSNumber with a int, to see if it is 0 or 1. Here is the code:

id i = [dictionary objectForKey:@"error"]; //class = NSCFNumber

NSLog(@"%@ == 0 -> %@", i, i == 0);
NSLog(@"%@ == 0 -> %@", i, [i compare:[NSNumber numberWithBool:NO]]);

我对方法进行了尝试,但结果为 null:

I tried this to methods but I get null as result:

2010-10-17 21:57:49.065 Api[15152:a0f] 0 == 0 -> (null)
2010-10-17 21:57:49.065 Api[15152:a0f] 0 == 0 -> (null)

你能帮帮我吗?

推荐答案

  1. 比较的结果是一个不是Objective-C对象的BOOL.因此,您应该使用 %@ 打印它.改用 %d(显示 0 或 1).

  1. The result of comparison is a BOOL which is not an Objective-C object. Therefore you should not print it using %@. Try %d instead (shows 0 or 1).

[a compare:b] 如果 a < 则返回 -1b,如果 a == b 则为 0,如果 a > 则为 1b.所以你的第二个结果是预期的.

[a compare:b] returns -1 if a < b, 0 if a == b and 1 if a > b. So your 2nd result is expected.

您不能直接将 NSNumber 与整数进行比较.i == 0 实际上是一个 pointer 比较,它检查 i 是否为 NULL (0),如果该数字存在,这当然是 FALSE.所以第一个结果也是预期的.

You cannot compare an NSNumber directly with an integer. That i == 0 is actually a pointer comparison which checks whether i is NULL (0), which of course is FALSE if that number exists. So the 1st result is also expected.

如果你想检查是否相等,使用[a isEqualToNumber:b].或者,您可以使用 [a intValue] 提取整数并直接与另一个整数进行比较.

If you want to check for equality, use [a isEqualToNumber:b]. Alternatively, you could extract the integer out with [a intValue] and compare with another integer directly.

所以以下应该可以工作:

So the followings should work:

NSLog(@"%@ == 0 -> %d", i, [i isEqualToNumber:[NSNumber numberWithInt:0]]);
NSLog(@"%@ == 0 -> %d", i, [i intValue] == 0);

如果数字"实际上是一个布尔值,最好使用 -boolValue.

If the "number" is in fact a boolean, it's better to take the -boolValue instead.

NSLog(@"%@ == 0 -> %d", i, ! [i boolValue]);

这篇关于将 NSNumber 与 int 进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to stop UIBarButtonItem text from truncating?(如何阻止UIBarButtonItem文本被截断?)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)
Android IllegalArgumentException: The tag for fragment_XXX is invalid. Received: layout-sw600dp/fragment_XXX_0(Android IlLegalArgumentException:Fragment_XXX的标签无效。收到:Layout-sw600dp/Fragment_XXX_0)
NSURLSessionTaskPriority seems to be ignored?(NSURLSessionTaskPriority似乎被忽略了?)
How to make dataWithEPSInsideRect vector rather than bitmap in vector format?(如何用EPSInside Rect将dataWithEPSInside Rect变成矢量而不是位图的矢量格式?)
HTTPS request using volley(使用 volley 的 HTTPS 请求)