NSPredicate 作用:筛选
常用于:
1、加条件筛选数组中的符合谓词的对象
+ (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...; 设定谓词过滤条件
- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate; 数组调用谓词进行过滤
2、用一个设定条件的谓词评估是否一个对象符合该谓词
- (BOOL)evaluateWithObject:(id)object
1 Student *chuxiao = [[Student alloc]init]; 2 Student *panxiaoliang = [[Student alloc]init]; 3 Student *lizhenggeng = [[Student alloc]init]; 4 5 [chuxiao info1]; 6 [panxiaoliang info2]; 7 [lizhenggeng info3]; 8 9 NSArray *arr = [[NSArray alloc]initWithObjects:chuxiao,panxiaoliang,lizhenggeng, nil]; 10 11 12 NSPredicate *stuPredicate1 = [NSPredicate predicateWithFormat:@"name beginsWith 'p'"]; 13 NSArray *arr1 = [arr filteredArrayUsingPredicate:stuPredicate1]; 14 NSLog(@"name beginsWith 'p':%@",arr1); 15 16 NSPredicate *stuPredicate2 = [NSPredicate predicateWithFormat:@"studentID = 1"]; 17 NSArray *arr2 = [arr filteredArrayUsingPredicate:stuPredicate2]; 18 NSLog(@"studentID = 1:%@",arr2); 19 20 NSPredicate *stuPredicate3 = [NSPredicate predicateWithFormat:@"name = 'lizhenggeng'"]; 21 NSArray *arr3 = [arr filteredArrayUsingPredicate:stuPredicate3]; 22 NSLog(@"name = 'lizhenggeng':%@",arr3); 23 24 NSPredicate *stuPredicate4 = [NSPredicate predicateWithFormat:@"name like 'l*'"]; 25 NSArray *arr4 = [arr filteredArrayUsingPredicate:stuPredicate4]; 26 if(arr4.count == 0) 27 { 28 NSLog(@"name like 'l*' not found!"); 29 } 30 else NSLog(@"name like 'l*':%@",arr4); 31 32 NSPredicate *mathRange80_90 = [NSPredicate predicateWithFormat:@"math >= 80 && math <= 90"]; 33 BOOL isIn = [mathRange80_90 evaluateWithObject:panxiaoliang]; 34 if(isIn) 35 { 36 NSLog(@"panxiaoliang's MathScore is between 80 and 90"); 37 } 38 else NSLog(@"out of the range");