Matt.M
Matt.M

Reputation: 1148

Objective-C - Comparing integers not working as expected

So my problem is this:

I am receiving a JSON string from across the network. When decoded (using SBJSON libraries), it becomes an NSDictionary that SHOULD contain a number of some sort for the key 'userid'. I say 'should' because when I compare the value to an int, or an NSINTEGER, or NSNumber, it never evaluates correctly.

Here is the comparison in code:

NSDictionary *userDictionary = [userInfo objectAtIndex:indexPath.row];

if ([userDictionary objectForKey:@"userid"] == -1) {
 //Do stuff
}

The value inside the dictionary I am testing with is -1. When I print it out to console using NSLog it even shows it is -1. Yet when I compare it to -1 in the 'if' statement, it evaluates to false when it should be true. I've even tried comparing to [NSNumber numberWithInt: -1], and it still evaluates to false.

What am I doing wrong? Thanks in advance for your help!

Upvotes: 7

Views: 8982

Answers (1)

Roxy Light
Roxy Light

Reputation: 5147

You are comparing a pointer to an object, not an integer itself. You must first convert the object into an integer:

if ([[userDictionary objectForKey:@"userid"] integerValue] == -1)
{
     //Do stuff
}

Upvotes: 16

Related Questions