Predicate

谓词

什么是谓词:

谓词:在计算机语言的环境下,谓词是指条件表达式的求值返回真或假的过程。

谓词基本用法:

基本谓词的用法,创建一个谓词,这个谓词的判断条件是汽车的name是否与Herbie相同
需要注意的是,如果不使用单引号的话,谓词格式将会把字符串理解成keyPath,如果使用单引号的话。谓词为理解为字符串

   //创建谓词
    NSPredicate *predicate;
    //谓词的判断条件
    predicate = [NSPredicate predicateWithFormat:@"name =='Herbie'"];
    //在这里判断是否匹配
    BOOL match = [predicate evaluateWithObject:car];
    if (match) {
        NSLog(@"match");
    }else {
        NSLog(@"Not match");
    }

谓词判断条件的方式

1,硬编码条件(不推荐)

predicate = [NSPredicate predicateWithFormat:@"engine.horsepower > 150"];

2,传递参数条件(推荐)

int horsePower = 50;
predicate = [NSPredicate predicateWithFormat:@"engine.horsepower > %d",horsePower];

3,占位符(先把位置站好,需要的时候再传递参数)(技术性条件):$符号开头

predicateTemplate = [NSPredicate predicateWithFormat:@"engine.horsepower > $POWER"];
varDict = @{@"POWER": @150};
predicate = [predicateTemplate predicateWithSubstitutionVariables:varDict];

谓词判断条件运算符

比较运算符:> < >= <= != <>

逻辑运算符:与 或 非 相对应的标示符 AND OR

predicate = [NSPredicate predicateWithFormat:@"(engine.horsepower > 50) AND (engine.horsepower < 200)"];
predicate = [NSPredicate predicateWithFormat:@"(engine.horsepower < 50) OR (engine.horsepower > 200)"];
原文地址:https://www.cnblogs.com/liukunpeng/p/3736708.html