问题描述
我尝试用谓词表达搜索参数:
NSPredicate * predicate = [NSPredicate predicateWithFormat:@name CONTAINS [ cd]%@ OR code CONTAINS [cd]%@ OR currency CONTAINS [cd]%@ AND continent.paid ==%@,searchString,searchString,searchString,[NSNumber numberWithBool:YES]];
我尝试为可能的字符串记录表达搜索参数只有continent.paid == YES。问题是最后一个表达式被忽略。搜索返回来自continent.paid == NO的数据以及正确的数据。
b p $ p>
[NSPredicate predicateWithFormat:@(name CONTAINS [cd]%@ OR code CONTAINS [cd]%@ OR currency CONTAINS [cd]%@)AND continent.paid ==%@ ,
searchString,searchString,searchString,[NSNumber numberWithBool:YES]];
据我所知,AND和OR在谓词中具有相同的优先级,并从左到右评估
。因此,在你的代码中,如果CONTAINS表达式的一个
为真,则谓词计算为 true
。
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?
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 evaluatedfrom left to right. Therefore in your code, the predicate evaluates to true
if oneof the "CONTAINS" expressions is true.
这篇关于iOS:NSPredicate不工作正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!