Objective-C - 比较不按预期工作的整数 [英] Objective-C - Comparing integers not working as expected
问题描述
所以我的问题是:
我从网络上收到一个JSON字符串。解码后(使用SBJSON库),它变成了一个NSDictionary,它应该包含一些关键字'userid'的类型。我说'应该',因为当我将值与int,NSINTEGER或NSNumber进行比较时,它永远不会正确评估。
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.
以下是代码中的比较:
NSDictionary *userDictionary = [userInfo objectAtIndex:indexPath.row];
if ([userDictionary objectForKey:@"userid"] == -1) {
//Do stuff
}
我测试的字典里面的值是-1。当我使用NSLog将其打印到控制台时,它甚至显示为-1。然而,当我在'if'语句中将它与-1进行比较时,如果它应该为真,则计算结果为false。我甚至尝试比较[NSNumber numberWithInt:-1],它仍然评估为假。
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!
推荐答案
您正在比较指向对象的指针,而不是整数本身。您必须先将对象转换为整数:
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
}
这篇关于Objective-C - 比较不按预期工作的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!