Luai Kalkatawi
Luai Kalkatawi

Reputation: 1492

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 :( ");
     }
}

Upvotes: 2

Views: 2522

Answers (2)

albertamg
albertamg

Reputation: 28572

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.

Upvotes: 3

Alladinian
Alladinian

Reputation: 35616

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)

Upvotes: 8

Related Questions