ios 值/对象的 NSDictionary 键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6120926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSDictionary Key For Value/Object?
提问by Syed Absar
Can we get the key for an object in an NSDictionary
by passing a particular value or object?
我们可以NSDictionary
通过传递特定的值或对象来获取对象的键吗?
回答by jscs
-[NSDictionary allKeysForObject:]
returns an NSArray
of all the keys whose objects match the passed object, where "match" is determined by isEqual:
.
-[NSDictionary allKeysForObject:]
返回NSArray
对象与传递对象匹配的所有键中的一个,其中“匹配”由 确定isEqual:
。
回答by AddisDev
To answer you question in a more specific manner, use the following to get a key for a particular object:
要以更具体的方式回答您的问题,请使用以下内容获取特定对象的密钥:
NSString *knownObject = @"the object";
NSArray *temp = [dict allKeysForObject:knownObject];
NSString *key = [temp lastObject];
//"key" is now equal to the key of the object you were looking for
回答by Denis Kutlubaev
This is how you can get a first key for object (in case it is an NSString
):
这是获取对象的第一个键的方法(如果它是NSString
):
NSArray *keys = [yourDic allKeysForObject:yourObject];
NSString *yourKey;
if ([keys count] > 0) {
yourKey = keys[0];
}
This handles if the object is not found in in the dictionary.
如果在字典中找不到对象,这将处理。