Can we get the key for an object in an NSDictionary
by passing a particular value or object?
Asked
Active
Viewed 5.9k times
82

jscs
- 63,694
- 13
- 151
- 195

Syed Absar
- 2,274
- 1
- 26
- 45
3 Answers
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
-
3but 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
-
2If 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
-
In the case the object is not a string, replace NSString with the object class. This is self explanatory. – AddisDev Sep 06 '13 at 18:28
-
6You might prefer `lastObject` to `objectAtIndex:0` to avoid throwing an exception if there are no such keys. – Jesse Rusak Sep 06 '13 at 18:50
-
3
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