82

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

0

3 Answers 3

149

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

Sign up to request clarification or add additional context in comments.

3 Comments

but remember: it gives all keys for objects matching 'isEqual' not '=='
@Kai: True. I should perhaps also add a note about it returning an NSArray although that should be clear from the method name.
If this isn't an FGITW question and answer, I don't know what is. Five upvotes just because I have a search shortcut in my browser.
44

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 Comments

In the case the object is not a string, replace NSString with the object class. This is self explanatory.
You might prefer lastObject to objectAtIndex:0 to avoid throwing an exception if there are no such keys.
Or even firstObject if you are using the latest SDK
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.