How to get object for key from NSDictionary?

Deadly 提交于 2019-12-12 08:28:43

问题


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.


回答1:


For starters, you might want to make that an actual string, like so:

[dict objectForKey:@"alba's window"];

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.




回答2:


Since iOS6 onwards, a convenient method for setting and accessing the object for a key from an NSDictionary is:

//Setting the object in NSMutableDictionary
dictionary[@"someKey"] = @"someString";

//Accessing the object
NSString *str = dictionary[@"someKey"];



回答3:


Make sure your dict isn't null; sending a message to a null object will silently fail and return null.

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".



来源:https://stackoverflow.com/questions/8486907/how-to-get-object-for-key-from-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!