Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumber with IF statement issue

I am loading data from a server but I have an issue that the value that I am returning is zero(0) while I can't go inside if. Please where would be the problem?

-(void)method1
{
     NSNumber *value = [data objectForKey:@"samount"];
     NSLog(@"number is -%@-", value); //number is -0-
     if (value == 0)
     {
          NSLog(@" OK :) ");
     }
     else 
     {
          NSLog(@"  Bad :( ");
     }
}
like image 956
Luai Kalkatawi Avatar asked Mar 25 '26 11:03

Luai Kalkatawi


2 Answers

Use isEqual:

if ([value isEqual:@(0)])

That will also evaluate correctly in case value is nil (where == comparison with floatValue or similar methods would fail)

like image 181
Alladinian Avatar answered Mar 27 '26 00:03

Alladinian


value is an object, and more precisely a NSString object (as per your comments in Alladinian's answer), but you are checking its address. You can convert your string to NSNumber with NSNumberFormatter and then check its value or rely on NSString's built-in methods: integerValue, floatValue, etc.

Assuming value is a NSNumber/NSString:

if ([value integerValue] == 0)

See Getting Numeric Values in NSString documentation and Accessing Numeric Values in the NSNumber documentation and pick the method that best suits your data type.

like image 26
albertamg Avatar answered Mar 27 '26 00:03

albertamg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!