美文网首页
NSPredicate用于查询和过滤

NSPredicate用于查询和过滤

作者: 跬步千里_LenSky | 来源:发表于2016-05-25 18:59 被阅读25次

    NSPredicate用于查询和过滤

    在SQL中作为查询条件通常用WHERE,但在COREDATA中作为查询条件就可以用到NSPredicate.

    NSPredicate 不单可以和COREDATA中的FetchRequest 配合使用。也可以与NSArray配合使用。

    NSPredicate 中支持的关键词和条件符:

    1、>,<,>=,<=,= 比较运算符。

    如:

    NSPredicate * qcondition= [NSPredicate predicateWithFormat:@"salary >= 10000"];

    2、字符串操作(包含):BEGINSWITH、ENDSWITH、CONTAINS

    如:

    @"employee.name BEGINSWITH[cd] '李'" //姓李的员工

    @"employee.name ENDSWITH[c] '梦'"  //以梦结束的员工

    @"employee.name CONTAINS[d] '宗'"  //包含有"宗"字的员工

    注:[c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。

    3、范围:IN  ,BWTEEN

    如:

    @"salary BWTEEN {5000,10000}"

    @"em_dept IN '开发'"

    4、自身:SELF,这个只针对字符数组起作用。

    如:

    NSArray * test = =[NSArray arrayWithObjects: @"guangzhou", @"beijing", @"shanghai", nil];

    @"SELF='beijing'"

    5、通配符:LIKE

    LIKE 使用?表示一个字符,*表示多个字符,也可以与c、d 连用。

    如:

    @"car.name LIKE '?he?'" //四个字符中,中间为he

    @"car.name LIKE '*jp'"  //以jp结束

    6、正则表达式:MATCHES

    如:

    NSString *regex = @"^E.+e$";//以E 开头,以e 结尾的字符。

    NSPredicate *pre= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    if([pre evaluateWithObject: @"Employee"]){

    NSLog(@"matches YES");

    }else{

    NSLog(@"matches NO");

    }

    7、逻辑运算符:AND、OR、NOT

    如:

    @"employee.name = 'john' AND employee.age = 28"

    8、占位符:

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

    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:

    @"Name1", @"NAME",nil];

    NSPredicate *pre=[preTemplate predicateWithSubstitutionVariables: dic];

    占位符就是字典对象里的key,因此你可以有多个占位符,只要key 不一样就可以了。

    对数组过滤:

    如:

    NSMutableArray *carsCopy = [carsmutableCopy];

    [carsCopyfilterUsingPredicate: predicate];//filterUsingPredicate和NSMutableArray构成新数组。

    NSLog (@"%@", carsCopy);

    predicate = [NSPredicatepredicateWithFormat:@"engine.horsepower > %d", 50];

    results = [cars filteredArrayUsingPredicate: predicate];

    NSLog (@"%@", results);

    相关文章

      网友评论

          本文标题:NSPredicate用于查询和过滤

          本文链接:https://www.haomeiwen.com/subject/hnptdttx.html