iOS备忘录iOS 专题

NSPredicate 谓词

2016-03-21  本文已影响2381人  秋月夜

开发中经常需要从集合中查找到某个或某些值,或者通过过滤得到想要的内容,这都是家常便饭的事儿。所以,我们常见的就是需要遍历集合,加条件判断,然后得到符合条件的结果。然而,遍历是件很耗内存的事儿,特别是在移动端开发,多重的for循环遍历,是要尽量避免的。此文主要是来介绍NSPredicate类,这种类似于SQL语句通过过滤集合内容的方式,来避免进行集合遍历的方法。

1. NSPredicate

The NSPredicate class is used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.

NSPredicate类是用来定义逻辑条件约束的获取或内存中的过滤搜索。

2. 基本语法

2.1 比较运算符

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age >= 55"];

2.2 集合运算符

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age BETWEEN {11, 55}"];

age代表了集合中对象的一个实例属性,此时集合中的对象是一个个的实体。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name IN {'Seven', 'Eight'}"];

2.3 逻辑运算符

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = 'One' && age = 11"];

2.4 字符串间运算符

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] 'F'"];

注: 字符串比较都是区分大小写和重音符号的。如:café和cafe是不一样的,Cafe和cafe也是不一样的。如果希望字符串比较运算不区分大小写和重音符号,请在这些运算符后使用[c],[d]选项。其中[c]是不区分大小写,[d]是不区分重音符号,其写在字符串比较运算符之后,比如:name LIKE[cd] 'cafe',那么不论name是cafe、Cafe还是café上面的表达式都会返回YES。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE[cd] 'T*'"];

2.5 %K、%@、$VALUE的用法

NSString *nameStr = @"name";
NSString *valueStr = @"Seven";
NSPredicate *predicate0 = [NSPredicate predicateWithFormat:@"%K CONTAINS %@", nameStr, valueStr];
NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"%K > $VALUE", @"age"];
NSPredicate *predicate1 = [pred1 predicateWithSubstitutionVariables:@{@"VALUE" : @1}];

2.6 实例运用

// 取出self.array2中  self.array2 & self.array1都不包含的元素
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)", self.array1];
NSLog(@"%@", [self.array2 filteredArrayUsingPredicate:predicate]);
    
// 取出self.array1 & self.array2 都包含的元素
predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", self.array1];
NSLog(@"%@", [self.array2 filteredArrayUsingPredicate:predicate]);
    
// 取出self.array1中  self.array2 & self.array1都不包含的元素
predicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)", self.array2];
NSLog(@"%@", [self.array1 filteredArrayUsingPredicate:predicate]);

3. 谓词过滤集合

其实谓词本身就代表了一个逻辑条件,计算谓词之后返回的结果永远为BOOL类型的值。而谓词最常用的功能就是对集合进行过滤。当程序使用谓词对集合元素进行过滤时,程序会自动遍历其元素,并根据集合元素来计算谓词的值,当这个集合中的元素计算谓词并返回YES时,这个元素才会被保留下来。请注意程序会自动遍历其元素,它会将自动遍历过之后返回为YES的值重新组合成一个集合返回。

4. GitHub

5. References

上一篇下一篇

猜你喜欢

热点阅读