views:

35

answers:

1

Is there any way of getting a key value from an NSDictionary based on its value? I can get the value based on the key in several ways but I need to get at the key.

Using the example below how would I be able to get the key if my value was QuestionType?

NSDictionary *question = [NSDictionary dictionaryWithObjectsAndKeys:  
                @"QuestionType", @"0",
                @"Answer", @"1",
                nil];
+2  A: 

You can use -[NSDictionary allKeysForObject:]. It returns an NSArray of keys, because there could be more than one key for any given object.

In your example:

NSDictionary *question = [NSDictionary dictionaryWithObjectsAndKeys:  
                @"QuestionType", @"0",
                @"Answer", @"1",
                nil];
for (NSString *key in [question allKeysForObject:@"QuestionType"]) {
    NSLog(@"Key: %@", key);
}

By the way, is there any particular reason why your keys (@"0" and @"1") are NSStrings? You can use any object that supports NSCopying as a key, so NSNumber might be a better choice here.

David