Predicates wrap some combination of expressions and operators and when evaluated return a BOOL.
The NSPredicate class is used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.
// 大概是说: Predicate根据组合表达式的计算结果返回一个BOOL值. 可用于约束搜索或内存过滤.
Creating a Predicate:
+ (NSPredicate *)predicateWithFormat:(NSString *)format, ...
Predicate Format String Syntax:
PS: apple 称这个 format 为文本解释器(predicate string parser), 和正则表达式完全不是一个东西.
空格和关键字大小写不敏感, 支持括号嵌套的表达式, 不做类型检查;
$variable
表示变量, ?是非法关键字;
支持
printf
网络的格式说明符, 其中%k和%@很重要.
%@ 对象值占位符, 一般是一个字符串, 数字, 日期等.
%K key path占位符,(key path 是什么? 看看KVC和KVO, 访问对象属性的技术.)
用%@指定字符串变量时, 它会被解释为带双引号的字符串, 用%K指定一个可变的属性
NSString *attributeName = @"firstName";
NSString *attributeValue = @"Adam";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@",
attributeName, attributeValue];
解析结果为:
firstName like “Adam”
.
单/双引号的变量(或替代变量的字符串)%@,%K,或$变量被解释为一个文本格式字符串,从而防止任何替换。在下面的例子中,解析结果为: firstName like “%@” (注意%@是单引号的)。
NSString *attributeName = @"firstName";
NSString *attributeValue = @"Adam";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like '%@'",
attributeName, attributeValue];
注意: 不能用一个%@代替整个 predicate format 表达式(entire predicate), 如下面的例子不能通过编译:
NSString *expression = @"firstName like Adam";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@", expression];
比较运算(Basic Comparisons)
=, ==
BETWEEN
以下例子的表达式相当于 ( betweenPredicate >=1 && betweenPredicate<= 10 )
NSPredicate *betweenPredicate =
[NSPredicate predicateWithFormat: @"attributeName BETWEEN %@", @[@1, @10]];
NSDictionary *dictionary = @{ @"attributeName" : @5 };
BOOL between = [betweenPredicate evaluateWithObject:dictionary];
if (between) {
NSLog(@"between");
布尔predicate
TRUEPREDICATE 解析为 true
FALSEPREDICATE 解析为 false
NSArray *numberArray = @[@1, @4, @5, @20]
NSPredicate *p
p = [NSPredicate predicateWithFormat:@"TRUEPREDICATE"]
NSLog(@"All numbers: %@", [numberArray filteredArrayUsingPredicate:p])
p = [NSPredicate predicateWithFormat:@"FALSEPREDICATE"]
NSLog(@"No numbers: %@", [numberArray filteredArrayUsingPredicate:p])