iOS 谓语 — NSPredicate
/实例化三个Person,并放入数组。
(5.) 字符串运算符:
Cocoa 提供了NSPredicate 用于指定过滤条件,谓词是指计算机中表示计算机真假值得函数
,使用起来有点像SQL的查询条件,主要用于从集合中分拣出符合条件的对象,也可以用字符串的正则匹配
/实例化三个Person,并放入数组。
NSMutableArray *array=[NSMutableArray arrayWithCapacity: 5];
Person *person1=[[Person alloc] init];
[person1 setPid: 1];
[person1 setName: @"Name1"];
[person1 setHeight: 168];
[array addObject: person1];
Person *person2=[[Person alloc] init];
[person2 setPid: 2];
[person2 setName: @"Name2"];
[person2 setHeight: 178];
[array addObject: person2];
Person *person3=[[Person alloc] init];
[person3 setPid: 3];
[person3 setName: @"Name3"];
[person3 setHeight: 188];
[array addObject: person3];
创建谓语,条件是pid > 1 并且height <188.0 其实谓词也是基于KVC的,也就是如果pid在person的成员变量***中那么此处写成***.pid>1
NSPredicate *predicate = [NSPredicate predicateWithFormat:@“pid>1 and height<188.0”];
int i = 0;
for(;i <[array count];i++){
Person *person = [array objectAtIndex:i];
// 遍历数组,输出符合谓词条件的Person的name
if ([predicate evaluateWithObject:person]){
NSLog(@“%@“,[person name]);
}
}
1 逻辑运算符:AND OR NOT
这几个运算符计算并 或 非的结果
2 范围运算符:BETWEEN IN
例 @“pid BETWEEN {1,5}”
@“name IN{Name1,name2}”
3 占位符
NSPredicate *preTemplate = [NSPredicate predicateWithFormat:@“name == $NAME”];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@“Name1”,@“NAME”,nil];
NSPredicate *pre = [preTemplate predicateWithSubstitutionVariables:dic];
站位符就是字段对象里的key ,因此你可以有多个占位符,只要key不一样就可以
4 快速筛选数组
前面我们使用谓词逐个判断数组内的对象是否符合,其实数组本身与更快捷的方法,直接筛选出一个符合谓词的新数组
NSPredicate *pre = [NSPredicate predicateWithFormat :@“pid >1”];
NSMutableArray *arrayPre = [array filteredArrayUsingPredicate:pre];
NSLog(@“%@“,[[arrayPre objectAtIndex:0]name]);