• NSPredicate简单介绍


    NSPredicate中主要的几种运算方式

    1.比较运算符 > 、< 、== 、 >= 、<= 、 !=
    例:@"number >= 99"

    2.逻辑运算符:AND、OR、NOT 这几个运算符计算并、或、非的结果。

    3.范围运算符:IN 、BETWEEN
    例:@"number BETWEEN {1,5}"
    @"address IN {'shanghai','nanjing'}"

    4.字符串本身:SELF
    例:@"SELF == 'APPLE'"

    5.字符串相关:BEGINSWITH、ENDSWITH、CONTAINS
    例: @"name CONTAIN[cd] 'ang'" //包含某个字符串
    @"name BEGINSWITH[c] 'sh'" //以某个字符串开头
    @"name ENDSWITH[d] 'ang'" //以某个字符串结束
    注:[c]不区分大小写 , [d]不区分发音符号即没有重音符号 , [cd]既不区分大小写,也不区分发音符号。

    6.通配符:LIKE
    例:@"name LIKE[cd] '*er*'" //*代表通配符,Like也接受[cd].
    @"name LIKE[cd] '???er*'"

    7.正则表达式:MATCHES
    例:NSString *regex = @"^A.+e$"; //以A开头,e结尾
    @"name MATCHES %@",regex

    用NSPredicate筛选两个数组的差异

    NSArray* array = @[@"aa",@"bb"];
    NSArray* array2 = @[@"aa",@"bb",@"cc",@"dd"];
    NSPredicate* thePredicate = [NSPredicate predicateWithFormat:@"NOT(SELF in %@)",array];
    NSArray* arr3 = [array2 filteredArrayUsingPredicate:thePredicate];
    NSLog(@"%@",arr3);
    

    上面的代码输出结果 arr3={@"cc" ,@"dd"}

    用NSPredicate筛选数组

    NSString *regex = @"^A.+e$";//以A 开头,以e 结尾的字符。
    NSPredicate *pre= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if([pre evaluateWithObject: @"Apple"]){

        NSLog(@"YES");

    }else{

       NSLog(@"NO");

    }

     

    关于NSPredicate的其他说明和注意事项,以及技巧

    动态属性名

    NSPredicate *p = [NSPredicate predicateWithFormat:@"name = %@", @"name1"];

    显然代码没有任何问题,但是这个不是最好的写法我建议如下写法:

    NSPredicate *preTemplate = [NSPredicate predicateWithFormat:@"name==$NAME"];

    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:

    @"name1", @"NAME",nil];

    NSPredicate *pre=[preTemplate predicateWithSubstitutionVariables: dic];

    这样看上去可能会让代码逻辑更清晰。

    当过滤条件字段都是动态的时候

    NSString *key = @"name";     
    NSString *value = @"name1";      
    NSPredicate *p = [NSPredicate predicateWithFormat:@"%@ = %@", key, value];

    然后当你执行到第三行的时候代码就会报错!

    逻辑上没错误啊!!!为什么会出错呢?
    NSPredicate要自动添加引号,所以最后得到的格式应该是@"'name' = 'name1'"。明显不对。要做的就是:

    NSPredicate *p = [NSPredicate predicateWithFormat:@"%K = %@", key, value];

     

  • 相关阅读:
    Pwn-level3
    【mysql】 mysql忘记密码
    【Linux】linux磁盘管理
    【Linux】Linux系统LVM管理及Raid
    【Git】git撤销与回滚
    【linux】Linux系统SELinux简介
    【Linux】Linux中的网络命令
    【Linux】linux中文本操作利器grep,awk,sed
    【Linux】linux正则表达式及通配符
    【Mysql】mysql数据备份
  • 原文地址:https://www.cnblogs.com/lhx2015/p/4635835.html
Copyright © 2020-2023  润新知