Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 976
Matt.M Avatar asked Nov 24 '09 06:11

Matt.M


1 Answers

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
}
like image 117
Ross Light Avatar answered Oct 06 '22 22:10

Ross Light