正文
Pid: 2];
[student2
set
Name: @
"dahuang"
];
[student2
set
Height: 178];
[array addObject: student2];
Student *student3=[[Student alloc] init];
[student3
set
Pid: 3];
[student3
set
Name: @
"erhuang"
];
[student3
set
Height: 188];
[array addObject: student3];
在上述的代码中,我们创建了一个可变数组,和三个小学生(-_-,不要吐槽我给他们的命名,懒得想..).
下面我们就要创建我们的谓词了,我们想要筛选出一个id 大于1 ,且升高小于180的小学生来,应该怎么做呢。
NSPredicate *pre = [NSPredicate predicateWithFormat:
@" pid>1 and height<188.0"];
int i=0;
for(i=0;i<[array count];i++){
Student *stu=[array objectAtIndex: i];
//遍历数组,输出符合谓词条件的Student 的name。
if ([pre evaluateWithObject: stu]) {
NSLog(@"11--%@",[stu name]);
}
}
谓词还可以帮我们做出一些列的筛选,如下:
//快速筛选数组内容 以及占位符的使用
NSPredicate *pre2 = [NSPredicate predicateWithFormat:@"pid>%d",1];
NSMutableArray *arrayPre2=[array filteredArrayUsingPredicate: pre2];
NSLog(@"%@",[[arrayPre2 objectAtIndex: 0] name]);
字符串的处理
//name以x开头的
NSPredicate *predicate3 = [NSPredicate predicateWithFormat:@"name BEGINSWITH 'x'"];
//name以g结尾的
NSPredicate *predicate4 = [NSPredicate predicateWithFormat:@"name ENDSWITH 'g'"];
//name中包含字符a的
NSPredicate *predicate5 = [NSPredicate predicateWithFormat:@"name CONTAINS 'a'"