问题
I try to express the search parameters with predicate:
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name CONTAINS [cd] %@ OR code CONTAINS [cd] %@ OR currency CONTAINS [cd] %@ AND continent.paid == %@",searchString,searchString,searchString,[NSNumber numberWithBool:YES]];
I try to express search parameters for possible string records ONLY where continent.paid==YES. The problem is that last expression is ignored. The search returns data from continent.paid==NO as well with the correct data. Whats wrong with it?
回答1:
You have to set parentheses:
[NSPredicate predicateWithFormat:@"(name CONTAINS [cd] %@ OR code CONTAINS [cd] %@ OR currency CONTAINS [cd] %@) AND continent.paid == %@",
searchString,searchString,searchString,[NSNumber numberWithBool:YES]];
As far as I know, "AND" and "OR" have the same precedence in a predicate, and are evaluated
from left to right. Therefore in your code, the predicate evaluates to true
if one
of the "CONTAINS" expressions is true.
来源:https://stackoverflow.com/questions/22514335/ios-nspredicate-doesnt-work-correct