iOS NSPredicate用法详解

在iOS开发中,系统提供了NSPredicate这个类给我们进行一些匹配、筛选操作,非常方便。在没有用这个类时,我们要获取两个数组中某些特定的元素时,需要写代码一一对比,但是使用了这个类,只需要三四行代码就够了。

为了演示,先定义一个person类

.h文件

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;

- (instancetype)initWithName:(NSString *)name
                         Age:(NSInteger)age;


+(Person *)personWithName: (NSString *)nsme
                      Age: (NSInteger)age;

@end

.m文件

#import "Person.h"

@implementation Person

- (instancetype)initWithName:(NSString *)name Age:(NSInteger)age {
    if (self = [super init]) {
        _name = name;
        _age = age;
    }

    return self;
}

+ (Person *)personWithName:(NSString *)nsme Age:(NSInteger)age {
    Person *person = [[Person alloc] initWithName:nsme Age:age];
    return person;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"name = %@, age = %ld",_name, _age];
}

@end

我在实现文件中重写了description方法,是为了一会在打印筛选结果时能打印出对象属性的值。

然后将person引入main文件中(为了方便演示,没有使用cocoa),创建出10个不同的person对象,并放进数组中。

// 创建出10个person对象,并加入数组
        NSMutableArray *muArray = [NSMutableArray array];
        for (int i = 0; i <10; i++) {
            Person *person = [Person personWithName:[NSString stringWithFormat:@"zhang%d",i] Age:i];
            [muArray addObject:person];
            
        }
        NSLog(@"muArray = %@", muArray);

ok,准备工作完成,下边主角闪亮登场。

NSPredicate使用时主要分两步走:第一步,定义谓词语句;第二步,根据要求,选择不同的方法执行谓词语句。

首先,我们来定义一个谓词语句,在定义谓词语句时,顺便会介绍谓词的语法

1)比较运算符

/**比较运算符
         * >:大于
         * <:小于
         * >=:大于等于
         * <=:小于等于
         * =,==:等于
         * !=,<>:不等于
         * between:左边的表达式等于右边的表达式的值或者介于它们之间。右边是一个有两个指定上限和下限的数值的数列(指定顺序的数列)。比如,1 BETWEEN { 0 , 33 },或者$INPUT BETWEEN { $LOWER, $UPPER }。
         **/
        // 例子:年龄属性大于3岁,注意:键路径不能用单引号引起来,否则会报错
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 3"];
2) 逻辑 运算符

        /**逻辑运算符
         * and/&&:与
         * or/||:或
         * not/!:非
         **/
        // 例子:年龄大于三岁或名字叫“zhang1”的,注意:字符串的值需要用单引号引起来,否则会报错,错误信息是:this class is not key value coding-compliant for the key zhang1.
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 3 || name = 'zhang1'"];

3)关系运算符

/**关系操作
         *  ANY,SOME:指定下列表达式中的任意元素。比如,ANY children.age < 18。
         *  ALL:指定下列表达式中的所有元素。比如,ALL children.age < 18。
         *  NONE:指定下列表达式中没有的元素。比如,NONE children.age < 18。它在<span id="5_nwp" style="padding: 0px; width: auto; height: auto; float: none;"><a target=_blank id="5_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=20&is_app=0&jk=f060e57c574871e8&k=%C2%DF%BC%AD&k0=%C2%DF%BC%AD&kdi0=0&luki=4&mcpm=0&n=10&p=baidu&q=65035100_cpr&rb=0&rs=1&seller_id=1&sid=e87148577ce560f0&ssp2=1&stid=9&t=tpclicked3_hc&td=1836545&tu=u1836545&u=http%3A%2F%2Fwww%2Ebubuko%2Ecom%2Finfodetail%2D920648%2Ehtml&urlid=0" target="_blank" mpid="5" style="padding: 0px; color: rgb(51, 51, 51); text-decoration: none;"><span style="padding: 0px; color: rgb(0, 0, 255); width: auto; height: auto;">逻辑</span></a></span>上等于NOT (ANY ...)。
         *  IN:等于SQL的IN操作,左边的表达必须出现在右边指定的集合中。比如,name IN { 'Ben', 'Melissa', 'Nick' }。
         **/
        // 例子:in<span id="6_nwp" style="padding: 0px; width: auto; height: auto; float: none;"><a target=_blank id="6_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=20&is_app=0&jk=f060e57c574871e8&k=%B9%D8%BC%FC%D7%D6&k0=%B9%D8%BC%FC%D7%D6&kdi0=0&luki=2&mcpm=0&n=10&p=baidu&q=65035100_cpr&rb=0&rs=1&seller_id=1&sid=e87148577ce560f0&ssp2=1&stid=9&t=tpclicked3_hc&td=1836545&tu=u1836545&u=http%3A%2F%2Fwww%2Ebubuko%2Ecom%2Finfodetail%2D920648%2Ehtml&urlid=0" target="_blank" mpid="6" style="padding: 0px; color: rgb(51, 51, 51); text-decoration: none;"><span style="padding: 0px; color: rgb(0, 0, 255); width: auto; height: auto;">关键字</span></a></span>:左边的关键字里必须包含右边的集合的元素
         NSPredicate *<span id="7_nwp" style="padding: 0px; width: auto; height: auto; float: none;"><a target=_blank id="7_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=20&is_app=0&jk=f060e57c574871e8&k=pre&k0=pre&kdi0=0&luki=7&mcpm=0&n=10&p=baidu&q=65035100_cpr&rb=0&rs=1&seller_id=1&sid=e87148577ce560f0&ssp2=1&stid=9&t=tpclicked3_hc&td=1836545&tu=u1836545&u=http%3A%2F%2Fwww%2Ebubuko%2Ecom%2Finfodetail%2D920648%2Ehtml&urlid=0" target="_blank" mpid="7" style="padding: 0px; color: rgb(51, 51, 51); text-decoration: none;"><span style="padding: 0px; color: rgb(0, 0, 255); width: auto; height: auto;">pre</span></a></span>dicate = [NSPredicate predicateWithFormat:@" name in {'zhang1','zhang4'}"];

4)数组操作

 /**数组操作
         *  array[index]:指定数组中特定索引处的元素。
         *  array[FIRST]:指定数组中的第一个元素。
         *  array[LAST]:指定数组中的最后一个元素。
         *  array[SIZE]:指定数组的大小。
         **/

以上就是对谓词的定义,我们可以看出,我是主要使用了predicateWithFormat:这个类方法进行定义的。

下面进入第二步:执行谓词语句。

1)、过滤对象是数组:使用- (void)filterUsingPredicate:(NSPredicate *)predicate; 针对可变数组进行过滤,过滤掉可变数组中不符合条件的- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate; 针对不可变数组进行过滤,将符合条件的元素组成一个新数组进行返回
2)、对单个对象进行判断过滤使用:- (BOOL)evaluateWithObject:(id)object; 向谓词对象发送该方法,参数是过滤的对象。常见于和正则表达式配合使用。

下边分别示范上边的三种方法。

a)、- (void)filterUsingPredicate:(NSPredicate *)predicate; 针对可变数组进行过滤

// 1、创建出10个person对象,并加入数组
        NSMutableArray *muArray = [NSMutableArray array];
        for (int i = 0; i <10; i++) {
            Person *person = [Person personWithName:[NSString stringWithFormat:@"zhang%d",i] Age:i];
            [muArray addObject:person];
            
        }
        NSLog(@"muArray = %@", muArray);
// 2、定义谓词语句:年龄属性大于3岁,注意:键路径不能用单引号引起来,否则会报错
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age > 3"];
// 3、对可变数组进行过滤
        [muArray filterUsingPredicate:<span id="4_nwp" style="padding: 0px; width: auto; height: auto; float: none;"><a target=_blank id="4_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=20&is_app=0&jk=f060e57c574871e8&k=pre&k0=pre&kdi0=0&luki=7&mcpm=0&n=10&p=baidu&q=65035100_cpr&rb=0&rs=1&seller_id=1&sid=e87148577ce560f0&ssp2=1&stid=9&t=tpclicked3_hc&td=1836545&tu=u1836545&u=http%3A%2F%2Fwww%2Ebubuko%2Ecom%2Finfodetail%2D920648%2Ehtml&urlid=0" target="_blank" mpid="4" style="padding: 0px; color: rgb(51, 51, 51); text-decoration: none;"><span style="padding: 0px; color: rgb(0, 0, 255); width: auto; height: auto;">pre</span></a></span>dicate];
        NSLog(@"可变数组过滤后的结果%@", muArray);
我们可以看到打印的结果是:

2015-06-17 11:58:23.126 NSPredicate[3183:277528] 可变数组过滤后的结果(
    "name = zhang4, age = 4",
    "name = zhang5, age = 5",
    "name = zhang6, age = 6",
    "name = zhang7, age = 7",
    "name = zhang8, age = 8",
    "name = zhang9, age = 9"
)

b)、- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate; 针对不可变数组进行过滤,将符合条件的元素组成一个新数组进行返回。

 // - (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)<span id="3_nwp" style="padding: 0px; width: auto; height: auto; float: none;"><a target=_blank id="3_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=20&is_app=0&jk=f060e57c574871e8&k=pre&k0=pre&kdi0=0&luki=7&mcpm=0&n=10&p=baidu&q=65035100_cpr&rb=0&rs=1&seller_id=1&sid=e87148577ce560f0&ssp2=1&stid=9&t=tpclicked3_hc&td=1836545&tu=u1836545&u=http%3A%2F%2Fwww%2Ebubuko%2Ecom%2Finfodetail%2D920648%2Ehtml&urlid=0" target="_blank" mpid="3" style="padding: 0px; color: rgb(51, 51, 51); text-decoration: none;"><span style="padding: 0px; color: rgb(0, 0, 255); width: auto; height: auto;">pre</span></a></span>dicate; 针对不可变数组进行过滤,将符合条件的元素组成一个新数组进行返回
        NSArray *beforeFilterArray = [NSArray arrayWithArray:(NSArray *)muArray];
        NSArray *afterFilterArray = [beforeFilterArray filteredArrayUsingPredicate:predicate];
        NSLog(@"不可变数组过滤结果%@", afterFilterArray);

我们可以看到 打印 结果是:

2015-06-17 11:58:23.126 NSPredicate[3183:277528] 不可变数组过滤结果(
    "name = zhang4, age = 4",
    "name = zhang5, age = 5",
    "name = zhang6, age = 6",
    "name = zhang7, age = 7",
    "name = zhang8, age = 8",
    "name = zhang9, age = 9"
)

c)、- (BOOL)evaluateWithObject:(id)object; 对数组中的每一个元素进行筛选

 NSMutableArray *matchObjArray = [NSMutableArray array];
        for (Person *item in muArray) {
            // A、判断是否满足条件
            // 判断语句:evaluateWithObject,符合过滤条件就返回yes
            if ([<span id="2_nwp" style="padding: 0px; width: auto; height: auto; float: none;"><a target=_blank id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=20&is_app=0&jk=f060e57c574871e8&k=pre&k0=pre&kdi0=0&luki=7&mcpm=0&n=10&p=baidu&q=65035100_cpr&rb=0&rs=1&seller_id=1&sid=e87148577ce560f0&ssp2=1&stid=9&t=tpclicked3_hc&td=1836545&tu=u1836545&u=http%3A%2F%2Fwww%2Ebubuko%2Ecom%2Finfodetail%2D920648%2Ehtml&urlid=0" target="_blank" mpid="2" style="padding: 0px; color: rgb(51, 51, 51); text-decoration: none;"><span style="padding: 0px; color: rgb(0, 0, 255); width: auto; height: auto;">pre</span></a></span>dicate evaluateWithObject:item]) {
                [matchObjArray addObject:item];
            }
        }
        
        NSLog(@"符合过滤条件的对象是:%@", matchObjArray);

筛选结果是:

2015-06-17 11:58:23.125 NSPredicate[3183:277528] 符合过滤条件的对象是:(
    "name = zhang4, age = 4",
    "name = zhang5, age = 5",
    "name = zhang6, age = 6",
    "name = zhang7, age = 7",
    "name = zhang8, age = 8",
    "name = zhang9, age = 9"
)

小结:以上三种方法都可以执行谓词短语,如果是对数组元素进行过滤的话,我们使用: - (void)filterUsingPredicate:(NSPredicate *)predicate、- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate;更方便,如果是只针对一个对象进行判断的话,使用 - (BOOL)evaluateWithObject:(id)object; 更方便。











iOS开发,谓词(NSPredicate)的用法:(一)基本用法

标签:ios开发   谓词   条件查询   nspredicate   

原文:http://blog.csdn.net/quanzheng92/article/details/46532021

猜你喜欢

转载自blog.csdn.net/love_coders/article/details/50837291