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.
如何从NSDictionary中的相应值获取密钥?我知道allKeys函数,但我们有一个方法,它返回单个值的单个键。
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".
好吧因为一个值可以多次在NSDictionary中,所以没有办法只说“给我这个值的关键”。但你可以说“给我所有包含这个值的键”。
NSArray* arrayOfKeys = [yourDictionary allKeysForObject:myObject];
NSArray * arrayOfKeys = [yourDictionary allKeysForObject:myObject];
If the value is only once in the dictionary, you can just extract it, using:
如果该值在字典中只有一次,您可以使用以下方法提取它:
YourObject* o = [arrayOfKeys firstObject];
YourObject * o = [arrayOfKeys firstObject];
But, always do a NIL and count check on this array. Out of bounds exceptions ahead!
但是,总是对这个数组执行NIL并计数检查。超出范围的例外!
P.S. Credits to @Hagile for firstObject
method instead of objectAtIndex:0
附:对于@Hagile,使用firstObject方法而不是objectAtIndex:0
#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".
好吧因为一个值可以多次在NSDictionary中,所以没有办法只说“给我这个值的关键”。但你可以说“给我所有包含这个值的键”。
NSArray* arrayOfKeys = [yourDictionary allKeysForObject:myObject];
NSArray * arrayOfKeys = [yourDictionary allKeysForObject:myObject];
If the value is only once in the dictionary, you can just extract it, using:
如果该值在字典中只有一次,您可以使用以下方法提取它:
YourObject* o = [arrayOfKeys firstObject];
YourObject * o = [arrayOfKeys firstObject];
But, always do a NIL and count check on this array. Out of bounds exceptions ahead!
但是,总是对这个数组执行NIL并计数检查。超出范围的例外!
P.S. Credits to @Hagile for firstObject
method instead of objectAtIndex:0
附:对于@Hagile,使用firstObject方法而不是objectAtIndex:0