比较NSNumber为0无法正常工作? [英] Comparing NSNumber to 0 not working?

查看:172
本文介绍了比较NSNumber为0无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个JSON解析器,并将该值加载到detailDataSourceDict变量中.当我尝试获取数组的valueForKey并将其与0进行比较时,它永远无法工作...

I have a JSON parser in my app, and I load the value into a detailDataSourceDict variable. When I try to get the valueForKey of the array and try to compare it to 0, it never works...

这是我的代码:

if (indexPath.row == 1) {
    NSNumber *rating = [detailDataSourceDict valueForKey:@"rating"];
    NSLog(@"Rating:  %@",rating);
    if (rating == 0) {
        cell.detailTextLabel.text = @"This sheet has not yet been rated.";
    }
    else {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"This sheet has a %@ star rating.",rating];
    }
    cell.textLabel.text = @"Rating";


}

我在JSON供稿中看到评级":"0",但是当评级为0时,它显示此工作表的星级为0.",而不是尚未对该工作表进行评级".

I see in my JSON feed that "rating":"0", but when the rating is 0, it shows "This sheet has a 0 star rating.", instead of "This sheet has not yet been rated."

有什么建议吗?谢谢.

推荐答案

NSNumber *rating是一个对象. 0是原始类型. 原始类型可以与==进行比较.对象不能;需要使用

NSNumber *rating is an object. 0 is a primitive type. Primitive types can be compared with ==. Objects cannot; they need to be compared for equality using isEqual:.

因此替换此:

rating == 0

具有:

[rating isEqual:@0]

(@0 NSNumber文字)

或者:

rating.integerValue == 0


您甚至会编译错误的代码的原因是0等于0x0,而0x0又等于nil(有点,保留细节). 因此,您当前的代码将与此等效:


The reason why your wrong code even compiles is that 0 is equal to 0x0 which in turn is equal to nil (kind of, sparing the details). So, your current code would be equivalent to this:

rating == nil

这篇关于比较NSNumber为0无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆