谓词-——搜索用

一,定义:

NSPredicate 用于定义一个逻辑条件,通过该条件可执行搜索或内存中的过滤操作。

谓词由NSPredicate 对象来代表,有3个子类:NSComparisonPredicate、NSCompoundPredicate和NSExpression。

 

 

二,过滤集合:

使用谓词来过滤不可变集合与过滤可变的区别是:

  使用谓词过滤不可变集合时,方法将会返回符合条件的集合元素组成的新集合;

  使用谓词过滤可变集合时,方法没有返回值,该方法直接剔除改集合中不符合谓词条件的元素。

eg:

NSPredicate *pred =[NSPredicate  preducateWithFormat:@"name CONTAINS ' 大王' "];

 

三,在谓词中使用占位符参数

%K:该占位符用于动态传入参数;

%@:该占位符用于动态设置属性值;

此外,

[NSPredicate predicateWithFormat:@"name CONTAINS $SUBSTR"];

 

 

四,

1.) 逻辑运算符:AND、OR、NOT

这几个运算符计算并、或、非的结果。
(2.) 范围运算符:BETWEEN、IN
例:
@”pid BETWEEN {1,5}”
@"name IN {'Name1','Name2'}"
(3.) 占位符:
NSPredicate *preTemplate = [NSPredicate predicateWithFormat:@"name==$NAME"];
NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:
@"Name1", @"NAME",nil];
NSPredicate *pre=[preTemplate predicateWithSubstitutionVariables: dic];
占位符就是字段对象里的key,因此你可以有多个占位符,只要key 不一样就可以了。
(4.) 快速筛选数组:
前面我们都是使用谓词逐个判断数组内的对象是否符合,其实数组本身有更为便捷的方法,
直接筛选出一个符合谓词的新数组。
NSPredicate *pre = [NSPredicate predicateWithFormat:@"pid>1"];
NSMutableArray *arrayPre=[array filteredArrayUsingPredicate: pre];
NSLog(@"%@",[[arrayPre objectAtIndex: 0] name]);
(5.) 字符串运算符:
BEGINSWITH、ENDSWITH、CONTAINS 分别表示是否以某字符串开头、结尾、包含。
他们可以与c、d 连用,表示是否忽略大小写、是否忽略重音字母(字母上方有声调标号)。
例:
@”name BEGINSWITH[cd] ‘He’”
判断name 是否以He 开头,并且忽略大小写、忽略重音字母。
(6.) LIKE 运算符:
LIKE 使用?表示一个字符,*表示多个字符,也可以与c、d 连用。
例:
@”name LIKE ‘???er*’” 与Paper Plane 相匹配。
(7.) SELF:
前面的数组中放的都是对象,如果数组放的都是字符串(或者是其他没有属性的类型),该
怎么写谓词呢?这里我们使用SELF。
例:
NSArray *arrays=[NSArray arrayWithObjects: @"Apple", @"Google", @"MircoSoft", nil];
NSPredicate *pre2 = [NSPredicate predicateWithFormat:@"SELF=='Apple'"];
(8.) 正则表达式:
NSPredicate 使用MATCHES 匹配正则表达式,正则表达式的写法采用international components
for Unicode (ICU)的正则语法。
例:
NSString *regex = @"^A.+e$";//以A 开头,以e 结尾的字符。
NSPredicate *pre= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if([pre evaluateWithObject: @"Apple"]){
printf("YES\n");
}else{
printf("NO\n");
}

posted @ 2015-05-19 21:05  尘恍若梦  阅读(363)  评论(0编辑  收藏  举报