zoukankan      html  css  js  c++  java
  • NSPredicate谓词

    NSPredicate——谓词(is)

    作用:判断条件表达式的求值返回真或假的过程
    
    使用步骤:
    1. 定义NSPredicate对象并指定条件
    2. 调用谓词的evaluateWithObject方法判断指定条件是否满足
    
    示例:
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self CONTAINS '1'"];
    NSString *text = @"1234";
    NSLog(@"%d", [predicate evaluateWithObject:text]);

    谓词示例(1)——传统方法

    1. 创建Person的对象数组
    2. 编写常规的查询判断姓名和年龄的过滤方法
    
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:personList.count];
    
    for (NSInteger i = 0; i < personList.count; i++) {
        Person *person = personList[i];
    
        // 用户年龄小于5 同时用户姓名中包含“1”字符串
        if (person.age < 5 && NSNotFound != [person.name rangeOfString:@"1"].location) {
            [result addObject:person];
        }
    }
    
    return result;

    谓词示例(2)——谓词方法

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS '1' && %K BETWEEN {%d, %d}", @"age", 5, 15];
    
    NSArray *result = [personList filteredArrayUsingPredicate:predicate];

    谓词的条件指令(1)——逻辑指令

    &&
    ||<
    <=
    ==
    >
    >=
    BETWEEN {}

    谓词的条件指令(2)——字符串匹配

    BEGANWITH:以指定字符开始
    ENDSWITH:以指定字符结束
    CONTAINS:包含指定字符,可使用修饰符
    c 不区分大小写
    d 不区分注音符号
    LIKE:使用通配符匹配
    ? 一个字符
    * 0个或多个字符

    提示

    1. 谓词中的匹配指令使用大写字母
    2. 谓词中可以使用格式字符串
    2. 如果通过对象的key path指定匹配条件,需要使用 %K
  • 相关阅读:
    169. Majority Element
    283. Move Zeroes
    1331. Rank Transform of an Array
    566. Reshape the Matrix
    985. Sum of Even Numbers After Queries
    1185. Day of the Week
    867. Transpose Matrix
    1217. Play with Chips
    766. Toeplitz Matrix
    1413. Minimum Value to Get Positive Step by Step Sum
  • 原文地址:https://www.cnblogs.com/HJiang/p/4280506.html
Copyright © 2011-2022 走看看