Objective-C - 比较整数未按预期工作
所以我的问题是这样的:
我从网络上接收到一个 JSON 字符串。解码时(使用 SBJSON 库),它变成一个 NSDictionary,应该包含键“userid”的某种类型的数字。我说“应该”是因为当我将值与 int、NSINTEGER 或 NSNumber 进行比较时,它永远不会正确计算。
这是代码中的比较:
NSDictionary *userDictionary = [userInfo objectAtIndex:indexPath.row];
if ([userDictionary objectForKey:@"userid"] == -1) {
//Do stuff
}
我正在测试的字典中的值是-1。当我使用 NSLog 将其打印到控制台时,它甚至显示它是 -1。然而,当我将它与“if”语句中的 -1 进行比较时,它的计算结果为 false,而它应该为 true。我什至尝试与 [NSNumber numberWithInt: -1] 进行比较,但它的计算结果仍然为 false。
我做错了什么?预先感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在将指针与对象进行比较,而不是与整数本身进行比较。您必须首先将对象转换为整数:
You are comparing a pointer to an object, not an integer itself. You must first convert the object into an integer: