Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate predicateWithFormat:argumentArray: Only Evaluating First Argument

I'm having some trouble using NSPredicate predicateWithFormat:argumentArray:. In this example, serverIDList is array of strings. Results is an array of NSManagedObjects with an attribute named "flid" which is a string.

NSMutableString *predicateString = [[NSMutableString alloc] init];

[predicateString appendString:@"(flid IN %@)"];

[results filterUsingPredicate:[NSPredicate predicateWithFormat:predicateString argumentArray:serverIDList]];

The problem is that [NSPredicate predicateWithFormat:predicateString argumentArray:serverIDList] evaluates to "flid IN '2155'", which is only the first value of the array serverIDList. I can't seem to get the predicate to evaluate the entire array. Is there something missing here?

Thanks!

like image 411
Gabriel Ortega Avatar asked Aug 05 '13 13:08

Gabriel Ortega


1 Answers

[NSPredicate predicateWithFormat:@"(flid IN %@)" argumentArray:serverIDList]

is equivalent to

[NSPredicate predicateWithFormat:@"(flid IN %@)", id1, id2, ..., idN]

where id1, ..., idN are the elements of the array serverIDList. That should explain why only the first element is evaluated.

What you probably want is

[NSPredicate predicateWithFormat:@"(flid IN %@)", serverIDList]

Remark: I would recomment not to create predicates as strings first. The chances for quoting or escaping errors are quite high. Use only predicateWithFormat with a constant format string. If you have to combine predicates dynamically at runtime, use NSCompoundPredicate.

like image 125
Martin R Avatar answered Sep 17 '22 13:09

Martin R