iOS技术交流园iOS开发技巧iOS开发攻城狮的集散地

iOS Foundation框架之谓词NSPredicate

2016-06-27  本文已影响1828人  断剑

很多初学者都很少接触NSPredicate,即使接触了NSPredicate 也不太了解NSPredicate的使用场景。此处根据我的使用,简单介绍一下NSPredicate的使用场景:

NSPredicate 主要是用来查询、条件过滤;
最常用的场景就是在自定义的数据模型对象中根据条件来查询相关信息,例如在手机通讯录中根据个人信息的Model所包含的name属性,来进行搜索
** 简言之** NSPredicate可以判断某个对象的某一个属性是否符合某一条件

1. NSPredict简单说明

2. NSPredict 表达式

在介绍NSPredict的使用之前,我们必须先要了解如何正确的书写谓词表达式

1.如果希望字符串比较运算符不区分大小写,可以再运算符后添加[c]
2.如果希望字符串比较运算符不区分重音符号,可以再运算符后添加[d]
一般都是在运算符后面添加[cd],代表不区分大小写和重音符号

2. NSPredict定义

//以一个NSPredict字符串来创建一个NSPredict对象
+ (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...;
+ (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat argumentArray:(nullable NSArray *)arguments;
+ (NSPredicate *)predicateWithFormat:(NSString *)predicateFormat arguments:(va_list)argList;

//通过一个对象来计算谓词的结果 真/假
- (BOOL)evaluateWithObject:(nullable id)object;
  ZZYPerson * person1 = [[ZZYPerson alloc]initWithName:@"zhang san" Age:@"21"];
  NSPredicate * pred1 = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@",@"san"];
  NSPredicate * pred2 = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] 'san'"];
  //注意第二种写法要将字符串用单引号包起来
   BOOL isHave = [pred1 evaluateWithObject:person1];
   NSLog(@"%d",isHave); //输出值为:1
   NSLog(@"%@---%@",person1.name,person1.age);//输出值为:zhang san---21

** 注意 **上述代码中pred2中的写法,字符串要用单引号括起来(比如sql语句中的字符串也要包含起来)

3. NSPredict 过滤查找集合元素

@interface NSArray<ObjectType> (NSPredicateSupport)
//根据谓词条件过滤数组,返回符合条件的元素组成的新数组
- (NSArray<ObjectType> *)filteredArrayUsingPredicate:(NSPredicate *)predicate;    // evaluate a predicate against an array of objects and return a filtered array
@end

@interface NSMutableArray<ObjectType> (NSPredicateSupport)
//根据谓词条件过滤数组,去掉数组中不符合条件的的元素
- (void)filterUsingPredicate:(NSPredicate *)predicate;    // evaluate a predicate against an array of objects and filter the mutable array directly
@end

@interface NSSet<ObjectType> (NSPredicateSupport)
////根据谓词条件过滤集合,返回符合条件的元素组成的新集合
- (NSSet<ObjectType> *)filteredSetUsingPredicate:(NSPredicate *)predicate NS_AVAILABLE(10_5, 3_0);    // evaluate a predicate against a set of objects and return a filtered set
@end

@interface NSMutableSet<ObjectType> (NSPredicateSupport)
//根据谓词条件过滤集合,去掉集合中不符合条件的的元素
- (void)filterUsingPredicate:(NSPredicate *)predicate NS_AVAILABLE(10_5, 3_0);    // evaluate a predicate against a set of objects and filter the mutable set directly
@end
  NSArray * array = @[@"libai",@"dufu",@"sushi",@"dumu"];
        
        NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF like %@",@"du*"];
        NSArray * resultArr = [array filteredArrayUsingPredicate:pred];
        NSLog(@"%@",resultArr);//输出值:(
    dufu,
    dumu
)
  
        NSSet * set = [NSSet setWithObjects:
                                  [[ZZYPerson alloc]initWithName:@"li si" Age:@"25"],
                                  [[ZZYPerson alloc]initWithName:@"zhang san" Age:@"20"],
                                  [[ZZYPerson alloc]initWithName:@"wang wu" Age:@"18"],nil
                                    ];
        
        NSPredicate * pred3 = [NSPredicate predicateWithFormat:@"name CONTAINS 'ang'"];
       NSSet * resultSet = [set filteredSetUsingPredicate:pred3];
        for (ZZYPerson * person  in resultSet) {
            NSLog(@"%@",person.name);
        }
 NSArray * array3 = @[[[ZZYPerson alloc]initWithName:@"li si" Age:@"25"],
                             [[ZZYPerson alloc]initWithName:@"zhang san" Age:@"20"],
                             [[ZZYPerson alloc]initWithName:@"wang wu" Age:@"18"]];
        NSArray * array4 = [array3 filteredArrayUsingPredicate:pred3];
        for (ZZYPerson * person  in array4) {
            NSLog(@"%@",person.name);
        }
//输出值:
 zhang san
 wang wu

4. NSPredict 的占位符参数

//设置NSPredict 中的可变参数,并计算结果
- (BOOL)evaluateWithObject:(nullable id)object substitutionVariables:(nullable NSDictionary<NSString *, id> *)bindings NS_AVAILABLE(10_5, 3_0); // single pass evaluation substituting variables from the bindings dictionary for any variable expressions encountered

//设置NSPredict 的可变参数,返回一个NSPredict 对象
- (instancetype)predicateWithSubstitutionVariables:(NSDictionary<NSString *, id> *)variables;    // substitute constant values for variables
 ZZYPerson * person1 = [[ZZYPerson alloc]initWithName:@"zhang san" Age:@"21"];
 ZZYPerson * person2 = [[ZZYPerson alloc]initWithName:@"li si" Age:@"25"];
ZZYPerson * person3 = [[ZZYPerson alloc]initWithName:@"stark" Age:@"11"];
        
        ZZYPerson * person4 = [[ZZYPerson alloc]initWithName:@"sunny" Age:@"30"];
        
         NSArray * array2 = @[person1,person2,person3,person4];
        
        NSString * name = @"age";
        NSString * age = @"3";
        NSPredicate * changePre1 = [NSPredicate predicateWithFormat:@"%K CONTAINS[cd] %@",name,age];
        
    NSArray * newArray2 = [array2 filteredArrayUsingPredicate:changePre1];
        for (ZZYPerson * person in newArray2) {
            NSLog(@"newArray2%@----%@",person.name,person.age);
        }
        
        //name中包含$SUBSTR的字串
        NSPredicate * changePre2 = [NSPredicate predicateWithFormat:@"%K CONTAINS[cd] $SUBSTR",@"name"];
        //指定$SUBSTR的值为sun
        NSPredicate * newChangePre2 = [changePre2 predicateWithSubstitutionVariables:@{@"SUBSTR":@"sun"}];
        
        NSArray * newArray3 = [array2 filteredArrayUsingPredicate:newChangePre2];
        for (ZZYPerson * person in newArray3) {
            NSLog(@"newArray3%@----%@",person.name,person.age);
        }
        

        NSPredicate * newChangePre3 = [changePre2 predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObjectsAndKeys:@"ang",@"SUBSTR", nil]];
        
        NSArray * newArray4 = [array2 filteredArrayUsingPredicate:newChangePre3];
        for (ZZYPerson * person in newArray4) {
            NSLog(@"newArray4%@----%@",person.name,person.age);
        }
//输出结果:
2016-06-27 23:07:11.820 ZZYNSPredicate[4540:96427] newArray2sunny----30
2016-06-27 23:07:11.820 ZZYNSPredicate[4540:96427] newArray3sunny----30
2016-06-27 23:07:11.820 ZZYNSPredicate[4540:96427] newArray4zhang san----21

上一篇下一篇

猜你喜欢

热点阅读