Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get key from respective value in a NSDictionary?

how to get key from respective value in a NSDictionary? I am aware of allKeys function but do we have a method which returns a single key for a single value.

like image 472
nitz19arg Avatar asked Feb 08 '13 07:02

nitz19arg


1 Answers

Well because a value can be in a NSDictionary multiple times, there is no way to just say "Give me the key for this value". But you CAN say "Give me all keys containing this value".

NSArray* arrayOfKeys = [yourDictionary allKeysForObject:myObject];

If the value is only once in the dictionary, you can just extract it, using:

YourObject* o = [arrayOfKeys firstObject];

But, always do a NIL and count check on this array. Out of bounds exceptions ahead!

P.S. Credits to @Hagile for firstObject method instead of objectAtIndex:0

like image 142
Wim Haanstra Avatar answered Oct 03 '22 06:10

Wim Haanstra