Pregunta

Say I have an NSDictionary and its keys are like this:

  1. @"123_000"
  2. @"223_000"
  3. @"123_111"
  4. @"223_111"

and so on. I want to get a NSArray or NSSet of all values whose corresponding keys contain substring @"123".

Of course I can just loop over the NSDictionary, but I suspect that there must be a less code heavy approach, probably involving KVC or NSPredicate, but I'm not really good in either of them.

¿Fue útil?

Solución

Yes, use NSPredicate.

First get allKeys from the dictionary. Then use filteredArrayUsingPredicate: to get the list of keys you want. Then use objectsForKeys:notFoundMarker: with your resulting array of keys to get the associated objects (the not found marker isn't an issue as we know all keys exist).

Otros consejos

To correct the answer of VaaChar:

In my example, I have a dictionary with keys and values only (vegan : 1, steak : 2, ...)

To check if my string is within these keys, I use:

NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@", keyword];
NSArray *categories     = [[self.categoriesAndIDs allKeys] filteredArrayUsingPredicate:predicate];

SELF represents the current object of the given array, in my case [self.categoriesAndIDs allKeys] so every string within the array will be checked for my "keyword", e.g. "steak" or "st" and the result will be an array with a string called "steak".

You could use something like this:

NSArray *resultArray = [[mainDict allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.@allKeys CONTAINS[c] %@", @"123"]];

"self.@allKeys" should return all keys of your dictionary and "CONTAINS[c] %@" checks if the key contains "123".

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top