定义(最常用到的方法):
1 NSPredicate *ca = [NSPredicate predicateWithFormat:(NSString *), ...];
Format:
(1)比较运算符>,<,==,>=,<=,!=
可用于数值及字符串
例:@"number > 100"
(2)范围运算符:IN、BETWEEN
例:@"number BETWEEN {1,5}"
@"address IN {'shanghai','beijing'}"
(3)字符串本身:SELF
例:@“SELF == ‘APPLE’"
(4)字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
例:@"name CONTAIN[cd] 'ang'" //包含某个字符串
@"name BEGINSWITH[c] 'sh'" //以某个字符串开头
@"name ENDSWITH[d] 'ang'" //以某个字符串结束
注:[c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。
(5)通配符:LIKE
例:@"name LIKE[cd] '*er*'" //*代表通配符,Like也接受[cd].
@"name LIKE[cd] '???er*'"
(6)正则表达式:MATCHES
例:NSString *regex = @"^A.+e$"; //以A开头,e结尾
@"name MATCHES %@",regex
通常情况下,根据一个条件在数组中查询出匹配的对象的方式有如下几种:
(1)遍历数组,然后将每一个Item和这个条件进行比对,过滤出匹配的对象
显然这个效率比较低
(2)iOS提供另一个效率较高的查询方法,谓词NSPredicate,使用方法如下
1 1.NSString 对象 2 3 NSArray *array =@["123", @"234" , @"345"]; 4 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [cd] %@", "2"]; 5 NSArray *filterdArray = [array filterdArrayUsingPredicate:predicate]; 6 NSLog(@"%@", filterdArray ); 7 //output : @"123", "234" 8 9 2.含有属性的对象 10 11 @interface Person: NSObject 12 { 13 NSString *_name; 14 NSString *_telephone; 15 NSInteger _id; 16 } 17 18 @property (nonatomic, copy) NSString *name; 19 @property (nonatomic, copy) NSString *telephone; 20 @property (nonatomic, assign) NSInteger id; 21 22 @end 23 // 24 25 1).等于查询 26 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", "Ansel"]; 27 NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate]; 28 29 2).模糊查询 30 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS %@", @"A"]; //predicate只能是对象 31 NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];