14

NSDictionaryのそれぞれの値からキーを取得する方法は?allKeys関数を知っていますが、単一の値に対して単一のキーを返すメソッドがありますか。

4

1 に答える 1

37

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

于 2013-02-08T07:36:37.210 に答える