NSDictionary Key For Value/Object? [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-31 10:56:11

问题


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


回答1:


-[NSDictionary allKeysForObject:] returns an NSArray of all the keys whose objects match the passed object, where "match" is determined by isEqual:.




回答2:


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



回答3:


This is how you can get a first key for object (in case it is an 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.



来源:https://stackoverflow.com/questions/6120926/nsdictionary-key-for-value-object

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