比较NSNumber为0无法正常工作?

编程入门 行业动态 更新时间:2024-10-19 20:22:47
本文介绍了比较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是原始类型. 原始类型可以与==进行比较.对象不能;需要使用 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无法正常工作?

本文发布于:2023-11-01 12:47:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549373.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法正常   工作   NSNumber

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!