0
votes

What is a good way of looking through a NSMutableDictionary to see if there is a key that corresponds to another variable?

Lets say i have a NSString "test" and a mutable dictionary that has some values and NSString keys for those values.

What would be a good way of reading through the dictionary values to see if any of its keys are "test".

Would i have to have a for loop to read through dictionary values or is there something already a part of NSDictionary object that will do this that I'm not seeing.

2

2 Answers

3
votes

You can use keysOfEntriesPassingTest: method to find all keys where the value equals @"test".

In the implementation below only the first key will be found. If you need all keys where the object is @"Test", do not assign *stop.

NSString *target = @"test";
NSSet *keys = [myDictionary keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) {
    return (*stop = [target isEqual:obj]);
}];
2
votes

If what you want is just the one whose key is exactly "test", I think you can just use objectForKey: to try to get the corresponding object. If the key doesn't exist, the returned object will be nil.