什么是谓词?
- 谓词是通过NSPredicate类,指定的逻辑条件作为约束条件,完成对数据的筛选。
- Cocoa中提供了NSPredicate类,指定过滤器的条件,将符合条件的对象保留下来。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age<25"];
for (Person *p in arrar) {
BOOL result = [predicate evaluateWithObject:p];
if (result) {
NSLog(@"符合条件:%@",p);
}
}
//将符合条件的保留
[arrar filterUsingPredicate:predicate];
//返回新的数组
NSArray * arr = [array filteredArrayUsingPredicate:predicate];
NSLog(@"返回新的数组:%@",arr);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age <= %d",30];
//谓词不区分大小写&& AND || OR
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name > 'bruse' && age < %d",30];
//关键字 注意字符串一定要添加''
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name IN {'rose', 'bruse'}"];
//{}可以是数组
NSArray * array = @[@"1",@"2",@"3",@"4"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name IN %@",array];
//检查某个字符串以「A」开头
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH ‘A’"];
//检查某个字符串以「Z」开头
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name ENDSWITH ‘Z’"];
NSString * str = @"a";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like ‘*%@*’",str];