基本概念:
cocoa中提供了NSPredicate类,指定过滤器的条件,将符合的对象保留下来
创建谓词:
NSPredicate *predicate=[NSPredicatepredicateWithFormat:@"age>25 and age<29"];
判断是否满足条件
[predicate evaluateWithObject:personObj]
对数组过滤
NSArray *newArr=[arrfilteredArrayUsingPredicate:predicate];
NSLog(@"%@",newArr);
NSPredicate提供的过滤条件多种多样
第一、对于数字
NSPredicate *predicate=[NSPredicatepredicateWithFormat:@"age>25 and age<29"];
第二、对于字符串
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name='jack_2'"];
in用法
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name in {'jack_2','tom_8'}"];
数组in用法
NSArray *array=[NSArray arrayWithObjects:@"jack_2",@"tom_8",nil];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name in %@",array];
第三、BEGINSWITH关键字
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name BEGINSWITH 't'"];
第四、CONTAINS关键词
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name CONTAINS 'a'"];
第五、like用法
NSString *s=[NSStringstringWithFormat:@"name like '*%@*'",@"c"];
NSPredicate *predicate=[NSPredicate predicateWithFormat:s];
第六、ENDSWITH
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name ENDSWITH '_8'"];
sample:
- //运算符
- NSPredicate *predicate=[NSPredicate predicateWithFormat:@"age>25 and age<29"];
- //字符串
- //NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name='jack_2'"];
- // NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name in {'jack_2','tom_8'}"];
- // NSArray *array=[NSArray arrayWithObjects:@"jack_2",@"tom_8",nil];
- // NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name in %@",array];
- //BEGINSWITH关键字
- // NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name BEGINSWITH 't'"];
- //CONTAINS关键词
- // NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name CONTAINS 'a'"];
- //
- NSString *s=[NSString stringWithFormat:@"name like '*%@*'",@"c"];
- NSPredicate *predicate=[NSPredicate predicateWithFormat:s];
- //ENDSWITH
- // NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name ENDSWITH '_8'"];
- //判断是否满足条件
- for(person *personObj in arr)
- {
- if([predicate evaluateWithObject:personObj])
- {
- // NSLog(@"%@",personObj);
- }
- }
- //对数组过滤
- NSArray *newArr=[arr filteredArrayUsingPredicate:predicate];
- NSLog(@"%@",newArr);