Comparing NSNumber to 0 not working?

Deadly 提交于 2019-12-03 09:46:58
Regexident

NSNumber *rating is an object. 0 is a primitive type. Primitive types can be compared with ==. Objects cannot; they need to be compared for equality using isEqual:.

Thus replace this:

rating == 0

with:

[rating isEqual:@0]

(@0 being a NSNumber literal)

or alternatively:

rating.integerValue == 0

The reason why your wrong code even compiles is that 0 is equal to 0x0 which in turn is equal to nil (kind of, sparing the details). So, your current code would be equivalent to this:

rating == nil

rating is a pointer to an NSNumber object, if you compare with == 0, you'll be comparing the pointer only.

If you want to compare the value with 0, you'll have to get the actual value using intValue, try;

if ([rating intValue] == 0) {
bryanmac

NSNumber is an object and you have to access it's value with the value accessors.

[NSNumber intValue];

See "Accessing Numeric Values" @:

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html

You want to change it from:

if (rating == 0) {

To

if ([rating intValue] == 0) {
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!