Can we get the key for an object in an NSDictionary by passing a particular value or object?
3 Answers
-[NSDictionary allKeysForObject:] returns an NSArray of all the keys whose objects match the passed object, where "match" is determined by isEqual:.
3 Comments
Kai Huppmann
but remember: it gives all keys for objects matching 'isEqual' not '=='
jscs
@Kai: True. I should perhaps also add a note about it returning an
NSArray although that should be clear from the method name.jscs
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.
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
AddisDev
In the case the object is not a string, replace NSString with the object class. This is self explanatory.
Jesse Rusak
You might prefer
lastObject to objectAtIndex:0 to avoid throwing an exception if there are no such keys.Abizern
Or even
firstObject if you are using the latest SDK