如何从 NSDictionary 获取键的对象?
在名为 dict 的字典中,键值对是:
"alba\U2019s window" = "Westindies 中的模特。";
并发送 objectForKey:
我收到类似“alba's window”的字符串。当我发送如下内容时:
[dict objectForKey:alba 的窗口];
我没有得到任何东西,它显示为空。
In dictionary named dict
the key value pair is:
"alba\U2019s window" = "A model in westindies.";
And to send objectForKey:
I am getting the string like "alba's window". When I send like following:
[dict objectForKey:alba's window];
I am not getting anything, it is showing null.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于初学者,您可能希望将其设为实际字符串,如下所示:
另请注意,
\U2019
不是'
;但是'
,这是一个完全不同的字符。更一般地说,坚持使用
[a-zA-Z0-9]+
作为字典键可能是一个好主意,除非您使用完全相同的字符串作为键以编程方式插入和检索。For starters, you might want to make that an actual string, like so:
Note also that
\U2019
is not'
; but’
, which is a different character entirely.And more generally, sticking to
[a-zA-Z0-9]+
for dictionary keys is probably a good idea, unless you are inserting and retrieving programmatically using the exact same string as a key.从 iOS6 开始,从 NSDictionary 设置和访问键对象的便捷方法是:
Since iOS6 onwards, a convenient method for setting and accessing the object for a key from an NSDictionary is:
确保您的
dict
不为空;向 null 对象发送消息将会失败并返回null
。检查键/值的另一种方法是简单地
NSLog(@"%@",dict);
这将显示字典的内容。请注意,当值包含空格时,此输出仅显示值周围的引号。另外,请确保您使用与键相同的字符串对 - 看起来除了
“alba's window”
之外,您还使用了“alba\U2019s window”
>。Make sure your
dict
isn't null; sending a message to a null object will silently fail and returnnull
.Another way to check your key/values is to simply
NSLog(@"%@",dict);
and this will show you the contents of the dictionary. Note that this output only shows quotes around values when the value contains a space.Also, make sure you're using the same pairs of strings as the key - it looks like you're using
"alba\U2019s window"
in addition to"alba's window"
.