Creating an NSPredicate from a String

I need to generate a predicate from several arrays of values. Therefore, I thought that I could initially form a string with all the values, and then pass this string for use in the predicate, i.e.

NSString* stringForPredicate = [[NSString alloc] init]; if (fromDate != nil) { stringForPredicate = [stringForPredicate stringByAppendingFormat:@"(Date > %@ AND Date < %@)", fromDate, toDate]; } 

There are further calculations that I do to form the final line of the predicate.

Now I want the predicate to use this line. I thought something like this would work:

  NSPredicate* filterPredicate = [NSPredicate predicateWithFormat:@"%@",stringForPredicate]; 

But this does not and throws an exception:

'Unable to parse format string'% @ ''

Is there any way to make this work?

thanks,

+4
source share
3 answers

The variable stringForPredicate actually contains format_string . Thus, you need to assign this variable instead of format_string and pass after that args , separated by commas, for example.

 NSSring *stringForPredicate = @"(Date > %@ AND Date < %@)"; NSPredicate* filterPredicate = [NSPredicate predicateWithFormat:stringForPredicate, fromDate, toDate]; 

For complex predicates:

 NSMutableArray *subPredicates = [NSMutableArray array]; if (fromDate != nil) { NSPredicate *from_predicate = [NSPredicate predicateWithFormat:@"Date > %@", fromDate]; [subPredicates addObject:from_predicate]; } if (toDate != nil) { NSPredicate *to_predicate = [NSPredicate predicateWithFormat:@"Date < %@", toDate]; [subPredicates addObject:to_predicate]; } NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates]; 
+15
source

Do not do it?

  NSPredicate* filterPredicate = [NSPredicate predicateWithFormat:stringForPredicate]; 

or do you need to do this

 NSPredicate* filterPredicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@",stringForPredicate]]; 

From reference documents

Format string summary

It is important to distinguish between different types of values ​​in a format. Note that single or double quotes (or a variable variable substitution) will call% @,% K or the variable $, which will be interpreted as a literal in string format and thus a replacement.

try it

 stringForPredicate = [stringForPredicate stringByAppendingFormat:@"(Date > %@) AND (Date < %@)", fromDate, toDate]; 
0
source

For those who use fast:

 let predicate = NSPredicate.init("Date > %@ AND Date < %@", fromDate, toDate); 
0
source

All Articles