LHF Objective-C语法(14)谓词
1、NSPredicate 谓词用于指定过滤条件,有点像SQL的查询条件,在计算机中表示计数真假值的函数,主要用于从集合分检出符合条件的对象,也可以用于字符串的正则匹配
例1
NSPredicate *pre = [NSPredicate predicateWithFormat:@"pid>1 and height<188"];
如果pid不是person的成员变量,而是在person的成员变量xxx中,那么此处要写成xxx.pid>1
1、逻辑运算符 AND OR NOT
2、范围运算符
@"pid BETWEEN {1,5}"
@"name IN {'Name1','Name2'}"
3、占位符
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name==$NAME"];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"Name1",@"NAME",nil];
NSPredicate *pre = [preTemplate predicateWithSubstitutionVariables:dic];
4、快速筛选数组
NSPredicate *pre = [NSPredicate predicateWithFormat:@"pid>1"];
NSMutableArray *arrayPre = [array filteredArrayUsingPredicate:pre];
NSLog(@"%@",[[arrayPre objectAtIndex:0] name]);
5、字符串运算符
@"name BEGINWITH[cd] 'na'" 判断name是否以na开头,[c]忽略大小写 [d]忽略重音字母
6、LIKE运算符
LIKE 使用?表示一个字符,*表示多个字符
@"name LIKE '???er*'" 与Paper Plane相匹配
7、SELF
NSArray *arrays = [ NSArray arrayWithObjects:@"Apple",@"Goolge",@"MicroSoft",nil];
NSPredicate *pre2 = [NSPredicate predicateWithFormat:@"SELF=='Apple'"];
8、正则表达式
NSString *regex = @"^A.+e$"; 以A开头,以e结尾
NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
if([pre evaluateWithObject:@"Apple"]){
NSLog(@"YES");
}else{
NSLog(@"NO");
}