Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating NSPredicate from string

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,

like image 534
user542584 Avatar asked Dec 06 '22 21:12

user542584


1 Answers

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];
like image 74
EmptyStack Avatar answered Dec 26 '22 03:12

EmptyStack