谓词NSPredicate的使用

      谓词是用来为数据添加过滤条件,从而更加精确的找到找到所描述条件的数据。苹果为我们封装好了NSPredicate类,我们可以很方便的得到我们需要的过滤条件。

      谓词的简单语法总结:

      比较运算:

 >
大于
<
小于
 >=
大于等于
 <=
小于等于
==
等于
!=
不等于
between
左边的表达式等于右边的表达式的值或者介于它们之间。
右边是一个有两个指定上限和下限的数值的数列
(指定顺序的数列)

 

       

          

 

 

 

 

 

   

 

 

 

 关系运算符:

ANY,SOME
指定下列表达式中的任意元素
ALL
指定下列表达式中的所有元素
NONE
指定下列表达式中没有的元素。
IN
左边的表达必须出现在右边指定的集合中。
比如,name IN { '昊天', '望舒', '墨雪' }。
BEGINSWITH
以xx开头
ENDSWITH
以xx结尾
CONTAINS
其中包含xx
like
匹配任意多个字符

 

 

 

 

 

 

 

 

 

 

 

 

1.查找数组中

NSArray *humans = [NSArray arrayWithObjects:
                        [Human personWithName:@"cat" andAge:0],
                        [Human personWithName:@"dog" andAge:1],
                        [Human personWithName:@"bird" andAge:2],
                        [Human personWithName:@"tiger" andAge:3],
                        [Human personWithName:@"lion" andAge:4],
                        [Human personWithName:@"monkey" andAge:5],
                        [Human personWithName:@"cow" andAge:6],
                        [Human personWithName:@"dargen" andAge:7],
                        [Human personWithName:@"bear" andAge:8], nil];
    //使用谓词条件运算符
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 5"];
    NSArray *array1 = [humans filteredArrayUsingPredicate:predicate];//将谓词添加到数组中
    NSLog(@"%@",array1);

//使用谓词中的in进行过滤
    predicate = [NSPredicate predicateWithFormat:@"name IN {'bird','lion'}"];
    NSArray *array2 = [humans filteredArrayUsingPredicate:predicate];
    NSLog(@"%@",array2);

 //使用between
    predicate = [NSPredicate predicateWithFormat:@"age between {2,5}"];
    NSArray *array3 = [humans filteredArrayUsingPredicate:predicate];
    NSLog(@"%@",array3);

 //使用like
    predicate = [NSPredicate predicateWithFormat:@"name like '?o*'"];//?表示一个字符串,且第二个字符串为o
    NSArray *array5 = [humans filteredArrayUsingPredicate:predicate];
    NSLog(@"%@",array5);

 

 //使用BEGINSWITH
    predicate = [NSPredicate predicateWithFormat:@"name beginswith 'd'"];
    NSArray *array4 = [humans filteredArrayUsingPredicate:predicate];
    NSLog(@"%@",array4);

原文地址:https://www.cnblogs.com/moxuexiaotong/p/4972511.html