0
votes

I am having NSMutableDictionary (subjectValue) which contains value and keys. I want to filter based on the values searched for in search bar. So, I used the code like below.

NSArray *allvalues = [subjectValue allValues];
NSArray *filteredValues = [allvalues filteredArrayUsingPredicate:predicate];

Now, filteredValues will have the values that are based on the search word.

Now, I want to get the Keys also for the filtered values got from the above result. I know how to get all values and all, but i want to get the keys for the filtered result.

Please advise how can i get that?

THIS IS NOT DUPLICATE OF THIS QUESTION. Existing Query Link

What has been asked in the above link is, how to retrieve all values based on the predicate search. What I'm asking is beyond that. I already have got all filtered values, I want to get keys for that filtered values. My question is different.

2
What they are asking is, how to retrieve all values based on the predicate search. What I'm asking is beyond that. I already have got all filtered values, I want to get keys for that filtered values. This question is different from stackoverflow.com/questions/16556905/… - user1953977
I know getting all Keys. Please check my question, I need to get Keys for some values only. - user1953977
You could use - keysOfEntriesPassingTest: to get an NSSet of the keys (based on a predicate that would be evaluated against values) and then - objectsForKeys:notFoundMarker: to get an NSArray of the values. - Alladinian

2 Answers

1
votes

There is a function keysOfEntriesPassingTest in NSDictionary. Is that what you are looking for? Example:

NSDictionary *subjectValue = @{@"1":@"A", @"2":@"B", @"3":@"C", @"4":@"D"};
NSArray *filteredValues = @[@"B", @"D"];


NSSet *keys = [subjectValue keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
    return [filteredValues containsObject:obj];
}];
NSLog(@"%@", keys.description);

The output I get for that is {(4,2)} (NSSet)

0
votes

I doubt that you can get the keys for given values by a predicate-like method. So if you have to enumerate the dictionary anyway, use something like this

 __block NSMutableDictionary * filteredDictionary = [NSMutableDictionary dictionary];
  [subjectValue enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    if ([obj matchesTheConditionOfThePredicate]) {
      filteredDictionary[key] = obj;
    }
  }];