1、常用创建方式
NSPredicate *predicate = [NSPredicate predicateWithFormat:@""];
2、Format:的格式
2.1 比较运算符 >,<,==,>=,<=,!=
// 说明:Person类要自己写,这里就不贴代码了
Person *p1 = [[Person alloc] initWithName:@"test1" AndAge:12];
Person *p2 = [[Person alloc] initWithName:@"test2" AndAge:23];
Person *p3 = [[Person alloc] initWithName:@"test3" AndAge:101];
Person *p4 = [[Person alloc] initWithName:@"test4" AndAge:120];
NSArray *arr = @[p1,p2,p3,p4];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age>100&&name=='test4'"];
// 注意这个语法里面字符串要用单引号
NSArray *result = [arr filteredArrayUsingPredicate:predicate];
// 打印输出结果
NSLog(@"%@",result);
2.2 范围运算符,in(则表示在后面的{}中是否包含),between(在某个范围内,如:age between{15,25}等价于 15<=age<=25)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age between {15,25}"];
或者
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name in {'test1','test2'}"];
2.3 对象本身self 如@"self == 'apple'"(也可以是NSNumber)
NSArray *arr = @[@"ss",@"dddd",@"apple"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self == 'apple'"];
// 注意这个语法里面字符串要用单引号
NSArray *result = [arr filteredArrayUsingPredicate:predicate];
// 打印输出结果:apple
2.4 字符串相关
:BEGINSWITH、ENDSWITH、CONTAINS
例:@"name CONTAINS[cd] 'ang'" //包含某个字符串
@"name BEGINSWITH[c] 'sh'" //以某个字符串开头
@"name ENDSWITH[d] 'ang'" //以某个字符串结束
NSArray *arr = @[@"yangjie",@"zhangsan",@"lisi"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self contains[cd] 'ng'"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self beginswith[c] 'y'"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self endswith[d] 'i'"];
// 注意这个语法里面字符串要用单引号
NSArray *result = [arr filteredArrayUsingPredicate:predicate];
// 打印输出结果
NSLog(@"%@",result);
2.5通配符:LIKE
例:@"name LIKE[cd] 'er'" //代表通配符,Like也接受[cd].
@"name LIKE[cd] '???er'"
NSArray *arr = @[@"yangjie",@"zhangsan",@"lisi",@"ang",@"tangddd",@"fangxxx"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self like[cd] 'ang*'"];
// 注意这个语法里面字符串要用单引号
NSArray *result = [arr filteredArrayUsingPredicate:predicate];
// 打印输出结果
NSLog(@"%@",result);
2.6正则表达式:MATCHES
例:NSString *regex = @"^A.+e$"; //以A开头,e结尾
@"name MATCHES %@",regex