Objective-C 傻瓜书:如何从 NSDictionary 中获取值?
所以我从 NSDictionary 中提取值是最困难的。现在我只有一个从 JSON 调用填充的字典,它只包含一个名为“Success”、值为 0 或 1 的键。
如何对该值执行条件来检查它是 0 还是 1?我尝试了很多事情,但一无所获。这是我当前的代码:
[[jsonDictionary objectForKey:@"Success"] isEqualToNumber:1]
我收到 passing argument 1 of 'isEqualToNumber:' madepointer from integer without a cast'
作为警告,无论如何,应用程序在遇到该行时都会崩溃。
还有一个子问题,objectForKey
和 valueForKey
之间有什么区别?我应该默认使用哪一个?
不管怎样,这个 Objective-C 菜鸟真的很感激在这方面的一些帮助。提前致谢!
so I'm having the most difficult of time pulling values out of an NSDictionary
. Right now I just have a dictionary that is populated from a JSON call and it only contains a key named 'Success' with a value of 0 or 1.
How do I do a conditional on that value to check if its 0 or 1? I've tried a bunch of things, but I'm not getting anywhere. Here's my current code:
[[jsonDictionary objectForKey:@"Success"] isEqualToNumber:1]
I'm getting passing argument 1 of 'isEqualToNumber:' makes pointer from integer without a cast'
as a warning, and the app crashes when it hits that line anyway.
And a subquestion, what's the difference between objectForKey
and valueForKey
? Which one should I use by default?
Anyway, this noob in Objective-C would truly appreciate some help on this. Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于字典包含 Objective-C 对象,因此包含数字的条目是一个
NSNumber
实例。NSNumber
提供了一个方便的方法-intValue
,用于提取其底层int
值:请注意,
NSNumber
还有其他便利提取其底层值作为其他 C 数据类型的方法。在大多数情况下,您应该使用
-objectForKey:
而不是-valueForKey:
。 前者是获取字典中条目的规范方法并在NSDictionary
中声明。后者在NSObject
中声明,并在键值编码上下文中使用,其中密钥必须是有效的 KVC 密钥,并且有额外的处理 - 例如,如果您使用- valueForKey:
在具有以 @ 开头的键的字典中,该字符将从键中删除并调用[super valueForKey:key]
。Since dictionaries contain Objective-C objects, an entry containing a number is an
NSNumber
instance.NSNumber
provides a convenience method,-intValue
, for extracting its underlyingint
value:Note that
NSNumber
has other convenience methods for extracting its underlying value as other C data types.In most cases, you should use
-objectForKey:
instead of-valueForKey:
. The former is the canonical method to obtain an entry in the dictionary and is declared inNSDictionary
. The latter is declared inNSObject
and is used in Key-Value Coding contexts, where the key must be a valid KVC key, and there’s additional processing — for instance, if you’re using-valueForKey:
in a dictionary with a key that starts with @, that character is stripped from the key and[super valueForKey:key]
is called.数字 1 不是对象指针。如果您想在 NSDictionary 中使用数字,请使用 NSNumber 实例。
The number 1 is not an object pointer. Use an NSNumber instance instead if you want to use a number in an NSDictionary.