Search NSArray for value matching value

Jonathan. picture Jonathan. · Mar 7, 2011 · Viewed 59.9k times · Source

I have an NSArray of objects, which has a particular property called name (type NSString).
I have a second NSArray of NSStrings which are names.

I'd like to get an NSArray of all the objects whose .name property matches one of the names in the second NSArray.

How do I go about this, fast and efficiently as this will be required quite often.

Answer

Lukasz picture Lukasz · Oct 26, 2011

Why not just to use predicates to do that for you?:

// For number kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

// For string kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

// For any object kind of value (yes, you can search objects also):
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];