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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 20:04:46  来源:igfitidea点击:

NSDictionary Key For Value/Object?

objective-ccocoa-touchiosnsdictionary

提问by Syed Absar

Can we get the key for an object in an NSDictionaryby passing a particular value or object?

我们可以NSDictionary通过传递特定的值或对象来获取对象的键吗?

回答by jscs

-[NSDictionary allKeysForObject:]returns an NSArrayof 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.

如果在字典中找不到对象,这将处理。