NSPredicate
1)介绍
官方文档:The NSPredicate class is used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.
NSPredicate用于数据的筛选。主要用于两个方法中
NSArray
- (NSArray )filteredArrayUsingPredicate:(NSPredicate )predicate;
NSMutableArray
- (void)filterUsingPredicate:(NSPredicate *)predicate;
还有NSSet和NSMutableSet也可以用这个类筛选。
2)筛选用法
[1]利用成员实例方法,例如筛选出大于3的字符串。
NSArray *array=@[@”jim”,@”wang”,@”jobk”,@”fjkkk”];
NSPredicate *pre=[NSPredicate predicateWithFormat:@”length>3”];
NSLog(@”NSpredicate %@”,[array filteredArrayUsingPredicate:pre]);
注意: lenght就是对数组成员执行[xxxx lenght]然后判断返回的NSUInteger值是否大于3。
——NSpredicate (
wang,
jobk,
fjkkk
)
[3]NSString其他方法使用NSPredicate ,比如integerValue
NSArray *array = @[@”2”, @”3”, @”4”, @”5”];
NSPredicate *pre = [NSPredicate predicateWithFormat:@”integerValue >= %@”, @3];
NSLog(@”%@”, [array filteredArrayUsingPredicate:pre]);
--(
3,
4,
5
)
[4]扩展到模型使用NSPredicate
Test.h
@interface Test : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *code;
@end
Test *test1 = [[Test alloc]init];
test1.name = @"西湖";
test1.code = @1;
Test *test2 = [[Test alloc]init];
test2.name = @"西溪湿地";
test2.code = @2;
Test *test3 = [[Test alloc]init];
test3.name = @"灵隐寺";
test3.code = @3;
NSArray *array = @[test1, test2, test3];
NSPredicate *pre = [NSPredicate predicateWithFormat:@"code >= %@", @2];
NSLog(@"%@", [array filteredArrayUsingPredicate:pre]);
---筛选出数组成员[test code]方法(code属性的get方法)返回值>=2的成员。这里的比较运算符同样也可以使用==、!=、<=、<。其实==不仅可以用来比较NSNumber对象,还可以用来判断NSString对象是否相同。
---NSPredicate *pre = [NSPredicate predicateWithFormat:@”name == %@”, @”西湖”];筛选出name是”西湖”的对象数组。
[5]NSPredicate中可以用CONTAINS(大小写都可以)来表示包含关系,
NSPredicate *pre = [NSPredicate predicateWithFormat:@”name CONTAINS %@”, @“湖”];可以查出西湖(当判断的时候需要忽略大小写可以使用[cd])
[6]比如判断字符串以某个字符串开头或者结尾,通配符的使用。
BEGINSWITH(已某个字符串开头, begins with)
NSString *targetString = @”h”;
NSPredicate *pre = [NSPredicate predicateWithFormat:@”name BEGINSWITH %@”,targetString];
ENDSWITH(已某个字符串结尾, ends with)
NSString *targetString = @”ing”;
NSPredicate *pre = [NSPredicate predicateWithFormat:@”name ENDSWITH %@”,targetString];
[7]通配符 LIKE
*代表一个或者多个或者是空
?代表一个字符
例:@”name LIKE[cd] ‘er‘” //*代表通配符,Like也接受[cd].
@”name LIKE[cd] ‘???er*’”
3)应用场景
2、使用
2.1 场景1:NSArray过滤,也就是文章开头的场景
NSArray *array = [[NSArray alloc]initWithObjects:@”beijing”,@”shanghai”,@”guangzou”,@”wuhan”, nil];
NSString *string = @”ang”;
NSPredicate *pred = [NSPredicate predicateWithFormat:@”SELF CONTAINS %@”,string];
NSLog(@”%@”,[array filteredArrayUsingPredicate:pred]);
2.2 场景2:判断字符串首字母是否为字母
NSString *regex = @”[A-Za-z]+”;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@”SELF MATCHES %@”, regex];
if ([predicate evaluateWithObject:aString]) {
}
2.3 场景3:字符串替换
NSError* error = NULL;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@”(encoding=\”)[^\”]+(\”)”
options:0
error:&error];
NSString* sample = @”“;
NSLog(@”Start:%@”,sample);
NSString* result = [regex stringByReplacingMatchesInString:sample
options:0
range:NSMakeRange(0, sample.length)
withTemplate:@”
1utf−8
2”];
NSLog(@”Result:%@”, result);
2.4 场景4:截取字符串
//组装一个字符串,需要把里面的网址解析出来
NSString *urlString=@”1Q84 BOOK1”;
//NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个
NSError *error;
//http+:[^\s]* 这个表达式是检测一个网址的。(?<=title>).*(?=中内文字的正则表达式
NSRegularExpression regex = [NSRegularExpression regularExpressionWithPattern:@”(?<=title\>).(?=
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
//从urlString当中截取数据
NSString *result=[urlString substringWithRange:resultRange];
//输出结果
NSLog(@”->%@<-“,result);
}
}
2.5 场景5:判断是否是手机号码或者电话号码
//组装一个字符串,需要把里面的网址解析出来
NSString *urlString=@”1Q84 BOOK1”;
//NSRegularExpression类里面调用表达的方法需要传递一个NSError的参数。下面定义一个
NSError *error;
//http+:[^\s]* 这个表达式是检测一个网址的。(?<=title>).*(?=中内文字的正则表达式
NSRegularExpression regex = [NSRegularExpression regularExpressionWithPattern:@”(?<=title\>).(?=
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
//从urlString当中截取数据
NSString *result=[urlString substringWithRange:resultRange];
//输出结果
NSLog(@”->%@<-“,result);
}
}
2.6 场景6:验证邮箱、电话号码有效性
//是否是有效的正则表达式
+(BOOL)isValidateRegularExpression:(NSString )strDestination byExpression:(NSString )strExpression
{
NSPredicate *predicate = [NSPredicatepredicateWithFormat:@”SELF MATCHES %@”, strExpression];
return [predicate evaluateWithObject:strDestination];
}
//验证email
+(BOOL)isValidateEmail:(NSString *)email {
NSString *strRegex = @”[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{1,5}”;
BOOL rt = [CommonTools isValidateRegularExpression:email byExpression:strRegex];
return rt;
}
//验证电话号码
+(BOOL)isValidateTelNumber:(NSString *)number {
NSString *strRegex = @”[0-9]{1,20}”;
BOOL rt = [CommonTools isValidateRegularExpression:number byExpression:strRegex];
return rt;
}
2.7 场景7:NSDate筛选
//日期在十天之内:
NSDate *endDate = [[NSDate date] retain];
NSTimeInterval timeInterval= [endDate timeIntervalSinceReferenceDate];
timeInterval -=3600*24*10;
NSDate *beginDate = [[NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval] retain];
//对coredata进行筛选(假设有fetchRequest)
NSPredicate *predicate_date =
[NSPredicate predicateWithFormat:@”date >= %@ AND date <= %@”, beginDate,endDate];
[fetchRequest setPredicate:predicate_date];
//释放retained的对象
[endDate release];
[beginDate release];