1、NSPredicate 谓词用于指定过滤条件,有点像SQL的查询条件,在计算机中表示计数真假值的函数,主要用于从集合分检出符合条件的对象,也可以用于字符串的正则匹配
例1
#import <Foundation/Foundation.h> @interface Person : NSObject { int pid; NSString *name; float height; } -(void) setPid:(int)pid; -(void) setName:(NSString*) name; -(void) setHeight:(float) height; -(int) pid; -(NSString*) name; -(float) height; @end //================================ @implementation Person -(void) setPid:(int)p{ pid = p; } -(void) setName:(NSString*) n{ [n retain]; [name release]; name = n; } -(void) setHeight:(float) h{ height = h; } -(int) pid{ return pid; } -(NSString*) name{ return name; } -(float) height{ return height; } -(void) dealloc{ [name release]; [super dealloc]; } @end //======================================= int main (int argc, const char * argv[]) { @autoreleasepool { NSMutableArray *array = [NSMutableArray arrayWithCapacity:5]; //实例化三个person放入数组 Person *p1 = [[Person alloc] init]; [p1 setPid:1]; [p1 setName:@"Tom"]; [p1 setHeight:168]; [array addObject:p1]; Person *p2 = [[Person alloc] init]; [p2 setPid:2]; [p2 setName:@"Ken"]; [p2 setHeight:178]; [array addObject:p2]; Person *p3 = [[Person alloc] init]; [p3 setPid:3]; [p3 setName:@"Tom"]; [p3 setHeight:188]; [array addObject:p3]; //创建谓词,条件是pid》1并且height《188 NSPredicate *pre = [NSPredicate predicateWithFormat:@"pid>1 and height<188"]; int i=0; for (;i<[array count]; i++) { Person *person = [array objectAtIndex:i]; //遍历数组,输出复合谓词条件的person的name if([pre evaluateWithObject:person]){ NSLog(@"%@",[person name]); } } [p1 release]; [p2 release]; [p3 release]; } return 0; }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");
}