NSPredicate
-
正则表达式
[NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"要匹配的正则"];
-
数组元素过滤
[NSPredicate predicateWithFormat:@"NOT (SELF in %@)", array];
[array1 filteredArrayUsingPredicate:predicate]NSArray * array = [NSArray arrayWithObjects:@"a", @"b",@"c", @"v", nil];
NSArray * array1 = [NSArray arrayWithObjects:@"a1", @"b", @"c", @"ab", nil];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"NOT (SELF in %@)", array];
NSLog(@"predicate --- %@",[array1 filteredArrayUsingPredicate:predicate]);
//运行结果:a1,ab
```
-
SELF
通配>
、<
、==
、>=
、<=
、!=
[NSPredicate predicateWithFormat:@"SELF == %@", @"要匹配的字符串"];
[array filteredArrayUsingPredicate:predicate]); -
LIKE
、BEGINSWITH
、ENDSWITH
、CONTAINS
、IN
、BETWEEN
[NSPredicate predicateWithFormat:@"SELF like %@", @"要匹配的字符串"];
IN 取两个数组的交集,NOT (SELF IN %@)不包含在数组%@中,SELF IN %@ 包含在数组%@中 -
?
、*
、[cd]
? 代表一个字符
- 代表任意多个字符
- c不区分大小写,d不区分重音符
-
过滤数组
set
filteredArrayUsingPredicate 返回符合条件的新集合。
filterUsingPredicate 提出集合中不符合条件的元素,不返回新的集合,还是原来的那个。
过滤不可变集合时,返回符合条件的新的集合。
过滤可变集合时,不返回新的集合,直接剔除不符合条件的元素。 -
筛选属性时,属性作为
key
,可用%K
表示 -
使用
$
修饰的字符,可以作为参数,在predicateWithSubstitutionVariables
中使用字典的形式赋值;在其他时候赋值,也方便产生多个条件类似的过滤器。Value 字符也可以替换为其他字符,只要前后统一即可,最好不要用关键字。NSPredicate *predTemp = [NSPredicate predicateWithFormat:@"%K CONTAINS $VALUE", @"name"];
NSPredicate *pred = [predTemp predicateWithSubstitutionVariables:@{@"VALUE" : @"jo"}];
[array filteredArrayUsingPredicate:pred]创建谓词,属性名改为age,要求这个age包含$VALUE字符串 NSPredicate *predTemp4 = [NSPredicate predicateWithFormat:@"%K > $VALUE", @"age"]; // 指定$VALUE的值为 20 NSPredicate *pred4 = [predTemp4 predicateWithSubstitutionVariables:@{@"VALUE" : @20}]; NSLog(@"%@", [array filteredArrayUsingPredicate:pred4]);//筛选到年级大于20的模型