Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing NSNumber to 0 not working?

Tags:

I have a JSON parser in my app, and I load the value into a detailDataSourceDict variable. When I try to get the valueForKey of the array and try to compare it to 0, it never works...

Here's my code:

if (indexPath.row == 1) {     NSNumber *rating = [detailDataSourceDict valueForKey:@"rating"];     NSLog(@"Rating:  %@",rating);     if (rating == 0) {         cell.detailTextLabel.text = @"This sheet has not yet been rated.";     }     else {         cell.detailTextLabel.text = [NSString stringWithFormat:@"This sheet has a %@ star rating.",rating];     }     cell.textLabel.text = @"Rating";   } 

I see in my JSON feed that "rating":"0", but when the rating is 0, it shows "This sheet has a 0 star rating.", instead of "This sheet has not yet been rated."

Any suggestions? Thanks.

like image 581
1789040 Avatar asked Nov 17 '12 15:11

1789040


People also ask

Is NSNumber integer?

NSNumber provides readonly properties that return the object's stored value converted to a particular Boolean, integer, unsigned integer, or floating point C scalar type.

Why use NSNumber?

The purpose of NSNumber is simply to box primitive types in objects (pointer types), so you can use them in situations that require pointer-type values to work. One common example: you have to use NSNumber if you want to persist numeric values in Core Data entities.


2 Answers

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 
like image 61
Regexident Avatar answered Oct 20 '22 12:10

Regexident


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) { 
like image 40
Joachim Isaksson Avatar answered Oct 20 '22 11:10

Joachim Isaksson