标签:谓词 nspredicate ios开发 objective-c 数组过滤
Cocoa中提供了NSPredicate类,指定过滤器的条件。将符合条件的对象保留下来。
下列列举常用的NSPredicate类的常用方法:
Person类含有name和age属性
初始化一个对象数组
NSMutableArray *array=[NSMutableArray array];
for (int i=0; i<10; i++) {
Person *person=[[Person alloc]init];
if (i<5) {
person.name=[NSString stringWithFormat:@"jack-%d",i];
}
else{
person.name=[NSString stringWithFormat:@"tom-%d",i];
}
person.age=@(20+i);
[array addObject:person];
}
//设置谓词条件
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"age<25"];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"age<%d",22];
// 可以用and or || &&
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"age>25 ||age<27"];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name=‘tom-8‘"];
//IN关键字
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"self.name IN{‘tom-8‘,‘jack-2‘}" ];
//数组
NSArray *inArray=@[@"tom-7",@"jack-3"];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"self.name in%@",inArray];
//BEGINWITH 检查某个字是否以**开头
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name BEGINSWITH ‘t‘ or name BEGINSWITH ‘j‘" ];
//ENDSWITH 检查某个字是否以**开头
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name ENDSWITH ‘-5‘"];
// CONTAINS 检查某个字是否以**开头
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name CONTAINS ‘-‘"];
//LIKE *4*表示4前后都是有内容的
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"name LIKE‘*4*‘"];
NSString *s=[NSString stringWithFormat:@"name like ‘*%@*‘",@"a"];
NSPredicate *predicate=[NSPredicate predicateWithFormat:s ];
//判断条件
for(Person *p in array)
{
BOOL ret=[ predicate evaluateWithObject:p];
if (ret) {
NSLog(@"%@",p);
}
}
//对数组过滤
NSArray *filteArray=[array filteredArrayUsingPredicate:predicate];
NSLog(@"%@",filteArray);
int i=10;
NSLog("%i",i);
标签:谓词 nspredicate ios开发 objective-c 数组过滤
原文地址:http://blog.csdn.net/u010804473/article/details/45220981