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
运行结果如下: