I need to form a predicate from multiple arrays of values. So I thought I can initially form a string with all the values, and then pass that string for usage in a 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 predicate string.
Now, I want the predicate to use this string. I thought that something like this would work:
NSPredicate* filterPredicate = [NSPredicate predicateWithFormat:@"%@",stringForPredicate];
But it doesnt and throws the exception:
'Unable to parse the format string "%@"'
Is there a way I can make this work?
thanks,
The stringForPredicate variable actually contains the format_string. So, you need to assign that variable in place of the format_string, and pass the args after that, seperated by commas, like this.
NSSring *stringForPredicate = @"(Date > %@ AND Date < %@)";
NSPredicate* filterPredicate = [NSPredicate predicateWithFormat:stringForPredicate, fromDate, toDate];
For compound 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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With