82

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

jscs
  • 63,694
  • 13
  • 151
  • 195
Syed Absar
  • 2,274
  • 1
  • 26
  • 45

3 Answers3

149

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

jscs
  • 63,694
  • 13
  • 151
  • 195
  • 3
    but remember: it gives all keys for objects matching 'isEqual' not '==' – Kai Huppmann May 25 '11 at 07:36
  • @Kai: True. I should perhaps also add a note about it returning an `NSArray` although that should be clear from the method name. – jscs May 25 '11 at 07:38
  • 2
    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. – jscs May 25 '11 at 07:57
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
AddisDev
  • 1,791
  • 21
  • 33
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.

Alex Zavatone
  • 4,106
  • 36
  • 54
Denis Kutlubaev
  • 15,320
  • 6
  • 84
  • 70