1

Is it possible to substitute reserved words, specifically OR and AND, into a predicateFormat?

I tried:

NSString *andOr = (isAnd ? @"AND" : @"OR");  // isAnd is a BOOL variable
NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"firstName == %@ %K lastName == %@",
                          user.firstName, andOr, user.lastName];

But I got:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Unable to parse the format string "firstName == %@ %K lastName == %@"

I tried %s (and also %S) instead of %K but got the same exception.

My working solution for now is to create the predicateFormat separately.

NSString *predicateFormat = [NSString stringWithFormat:
                             @"firstName == %%@ %@ lastName == %%@", andOr]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat,
                          user.firstName, user.lastName];

But, I was wondering if this could be done without creating predicateFormat separately.

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

2 Answers2

1

Yep, it can:

NSPredicate *firstName = [NSPredicate predicateWithFormat:@"firstName == %@", [user firstName]];
NSPredicate *lastName = [NSPredicate predicateWithFormat:@"lastName == %@", [user lastName]];
NSArray *subpredicates = [NSArray arrayWithObjects:firstName, lastName, nil];

NSPredicate *predicate = nil;
if (isAnd) {
  predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
} else {
  predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];
}
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
0

Using search bar text i am filtering the data.

Below code is simple and no need of any explanation

NSString *predFormat=[NSString stringWithFormat:@"FirstName CONTAINS[c] '%@' OR LastName CONTAINS[c] '%@' OR Phone CONTAINS[c] '%@'",searchValue,searchValue,searchValue]; //LIKE

NSPredicate *predicate = [NSPredicate predicateWithFormat:predFormat];

NSArray *tempData = [array filteredArrayUsingPredicate:predicate];

Hope this will work for you.. Happy coding....

GuruMurthy
  • 139
  • 1
  • 3