Objective-C - Comparing integers not working as expected

So my problem is this:

I get a JSON string from all over the network. When decoding (using SBJSON libraries), it becomes an NSDictionary, which MUST contain several views for the "userid" key. I say "must" because when I compare the value with int or NSINTEGER or NSNumber, it never evaluates correctly.

Here is a comparison in the code:

NSDictionary *userDictionary = [userInfo objectAtIndex:indexPath.row]; if ([userDictionary objectForKey:@"userid"] == -1) { //Do stuff } 

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

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

+7
json comparison integer objective-c
source share
1 answer

You are comparing a pointer to an object, not an integer. First you must convert the object to an integer:

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

All Articles