Searching NSArrays with NSPredicate

Nov 19, 2010   #cocoa  #ios 

If you have used Core Data before, you most likely know NSPredicate for querying data. But you probably have not been aware that you can use NSPredicate for searching in a NSArray containing KVC compliant objects:

// Elements in the input array must be KVC-compliant for "name"
- (NSArray *)searchArray:(NSArray *)inputArray forObjectsWithName:(NSString *)name {
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", name];
  return [inputArray filteredArrayUsingPredicate:predicate];

You can use all sorts of operators that are supported by NSPredicate, like BEGINSWITH or CONTAINS.