Andrey Chernukha Andrey Chernukha - 5 months ago 12
Objective-C Question

How to filter NSDictionary by substring in its keys?

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.

Answer

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).