nspredicate 谓词的主要用于以下几个方面:
(一)已知数组NSArray都有一个filteredArrayUsingPredicate方法,可以根据指定的nspredicate对象进行内容过滤。
(二) 除此之外Core Data框架中可以为查询请求NSFetchRequest类的对象指定nspredicate对象作为查询条件。
(三)nspredicate类还可以使用matches 进行设置正则表达式,使用evaluateWithObject:对对象进行匹配并根据匹配是否成功返回BOOL值。
新建工程如下:
编辑首控制器的.m文件 进行验证如下:
//
// ViewController.m
// 正则表达式的使用
//
// Created by apple on 15/10/2.
// copyright (c) 2015年 LiuXun. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 谓词nspredicate中的self只仅仅用于字符串数组。但用于指明数组中对象属性也不会出错,没必要
// 注意:self就相当于数组中的一个对象
NSArray *strArray = @[@"abcda",@"acddf",@"acddfdff",@"wqwewe",@"xydsdsd"];
// 使用谓词取出第三个字符是d的字符串
nspredicate *predicate = [nspredicate predicateWithFormat:@"self like '??d*' "];
NSArray *filteArray = [strArray filteredArrayUsingPredicate:predicate];
for(Nsstring *filterStr in filteArray){
NSLog(@"%@",filterStr);
}
// 谓词条件语句使用MATCHES 来匹配正则语句——匹配语句
Nsstring *regex1 = @"^E.+e$"; // 以E开头,以小写e结尾的字符
nspredicate *predicate2 = [nspredicate predicateWithFormat:@"self matches %@",regex1];
if ([predicate2 evaluateWithObject:@"Easdsdsddsdsdse"]) {
NSLog(@"匹配");
}
/*
当为数组指定过滤器时,调用数组的对象方法filteredArrayUsingPredicate:方法指定nspredicate对象。
当验证某个值或字符串对象是否符合指定的条件时 ,使用谓词的对象方法evaluateWithObject:方法
当Core Data中为查询请求指定条件时,使用NSFetchRequest类的对象方法 .predicate =XXX 赋值
*/
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// dispose of any resources that can be recreated.
}
@end
运行结果如下: