NSDictionary Key For Value/Object?

Objective CCocoa TouchIosNsdictionary

Objective C Problem Overview


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

Objective C Solutions


Solution 1 - Objective C

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

Solution 2 - Objective C

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

Solution 3 - Objective C

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSyed AbsarView Question on Stackoverflow
Solution 1 - Objective CjscsView Answer on Stackoverflow
Solution 2 - Objective CAddisDevView Answer on Stackoverflow
Solution 3 - Objective CDenis KutlubaevView Answer on Stackoverflow