开发者

Creating NSPredicate from string

开发者 https://www.devze.com 2023-03-03 14:58 出处:网络
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

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, toD开发者_运维百科ate];
    }

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];


Wont this do it?

  NSPredicate* filterPredicate = [NSPredicate predicateWithFormat:stringForPredicate];

or you have to do this

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

From the reference documents

Format String Summary

It is important to distinguish between the different types of value in a format string. Note also that single or double quoting variables (or substitution variable strings) will cause %@, %K, or $variable to be interpreted as a literal in the format string and so will prevent any substitution.

Try this

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


For those using swift:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号