NSPredicate:对self每个对象通过谓词进行筛选,判断是否与条件相匹配。原理和用法都类似于SQL查询中的where,作用相当于数据库的过滤取。主要用于从集合中分拣出符合条件的对象,也可以用于字符串的正则匹配
第一、contains 判断
NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];
NSString *string = @"ang";
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF CONTAINS %@",string];
NSArray *result=[array filteredArrayUsingPredicate:predicate];
NSLog(@"%@",result);
第二、in 判断
NSArray *array = [[NSArray alloc]initWithObjects:@"beijing",@"shanghai",@"guangzou",@"wuhan", nil];
NSArray *fieltArr=[[NSArray alloc] initWithObjects:@"welcome",@"to",@"beijing",nil];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF in %@",fieltArr];
NSArray *result=[array filteredArrayUsingPredicate:predicate];
NSLog(@"%@",result);
第三、like运算NSString *str=@"badger";
NSString *pattern=@"b??d*";
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF LIKE %@",pattern];
if([predicate evaluateWithObject:str])
{
NSLog(@"YES");
}else
{
NSLog(@"NO");
}
第四、正则表达式
NSString *pattern=@".*\\_\\d{3,5}×\\d{3,5}.jpg$";
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF matches %@",pattern];
NSString *str=@"fdas_300×50009.jpg";
if([predicate evaluateWithObject:str])
{
NSLog(@"YES");
}else
{
NSLog(@"NO");
}
NSPredicate的使用,码迷,mamicode.com
原文地址:http://blog.csdn.net/richard_rufeng/article/details/24674105