Slee
Slee

Reputation: 28268

dynamically generate NSPredicate from an NSArray

I have a large number of different NSObject types that all have different properties and I am trying to abstract out a single method that will allow me to filter the NSArrays of the objects by simply passing in an NSArray of properties I wish to filter on. The number keys I filter on vary from possibly 1 to whatever.

Here is an example of the filtering NSArray

NSArray *filterBy = [NSArray arrayWithObjects:
                       @"ManufacturerID",
                       @"CustomerNumber",nil];

These keys also exist in the objects of my NSArray I am filtering, so basically this would need to generate something like this:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"%K == %@ AND %K == %@",
                       [filterBy objectAtIndex:0], 
                       [items valueForKey: [filterBy objectAtindex:0],
                       [filterBy objectAtIndex:1], 
                       [items valueForKey: [filterBy objectAtIndex:1]];

Which would generate something like: ManufacturerID==18 AND CustomerNumber=='WE543'

Is it possible to do this?

Upvotes: 2

Views: 637

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243156

This is easy. Check it out:

NSMutableArray *subpredicates = [NSMutableArray array];
for (NSString *filterKey in filterBy) {
  NSString *filterValue = [items valueForKey:filterKey];
  NSPredicate *p = [NSPredicate predicateWithFormat:@"%K = %@", filterKey, filterValue];
  [subpredicates addObject:p];
}
NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];

Upvotes: 9

Related Questions