我的应用程序中有一个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是原始类型. 原始类型可以与==进行比较.对象不能;需要使用 isEqual: .
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无法正常工作?
发布评论