谓词(NSPredicate)

2016-02-19  本文已影响291人  chernyog

谓词(NSPredicate)

1. 什么是谓词

2. 常用运算符

2.1 比较运算符

2.2 逻辑运算符

2.3 字符串比较运算符

注: 字符串比较都是区分大小写和重音符号的。如:café和cafe是不一样的,Cafe和cafe也是不一样的。如果希望字符串比较运算不区分大小写和重音符号,请在这些运算符后使用[c],[d]选项。其中[c]是不区分大小写,[d]是不区分重音符号,其写在字符串比较运算符之后,比如:name LIKE[cd] 'cafe',那么不论name是cafe、Cafe还是café上面的表达式都会返回YES。

2.4 集合运算符

<h6>运算符内容,参考自http://www.cocoachina.com/ios/20160111/14926.html</h6>

3. %K、%@、$VALUE的用法

void $VALUE_K_的用法() {
    NSArray *array = @[[Student studentWithName:@"Tom" age:18 sex:1],
                       [Student studentWithName:@"Jack" age:19 sex:0],
                       [Student studentWithName:@"Zhuba" age:20 sex:1],
                       [Student studentWithName:@"Lisi" age:100 sex:0],
                       [Student studentWithName:@"Sunqi" age:0 sex:1],
                       [Student studentWithName:@"Rose" age:50 sex:0]
                       ];
    NSMutableArray *arrayM = [array mutableCopy];
    NSLog(@"%@", arrayM);
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"self.age >= 50"];
    [arrayM filterUsingPredicate:pred];
    NSLog(@"%@", arrayM);
    
    NSString *property = @"name";
    NSString *value = @"Jack";
    
    // %K 字段占位符
    // %@ 值占位符
    // 必须是 %K(K是大写字母)
    pred = [NSPredicate predicateWithFormat:@"%K contains %@", property, value];
    NSArray *tmpArray = [array filteredArrayUsingPredicate:pred];
    NSLog(@"tmpArray:%@", tmpArray);
    
    // $VALUE:VALUE只是一个普通字符串,当做标识使用,可以任意替换,但要统一!
    NSPredicate *tp = [NSPredicate predicateWithFormat:@"%K > $VALUE", @"age"];
    pred = [tp predicateWithSubstitutionVariables:@{@"VALUE" : @1}];
    NSArray *arr1 = [array filteredArrayUsingPredicate:pred];
    NSLog(@"arr1:%@", arr1);
    
    pred = [tp predicateWithSubstitutionVariables:@{@"VALUE" : @50}];
    NSArray *arr2 = [array filteredArrayUsingPredicate:pred];
    NSLog(@"arr2:%@", arr2);
}

4.运用举例

4.1 取出两个数组中的相同元素

void example() {
    NSArray *arr1 = @[@"ab", @"abc", @1];
    NSArray *arr2 = @[@"a", @"ab", @"abc", @"abcd"];
    // 取出arr2中  arr2 & arr1都不包含的元素
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)", arr1];
    NSLog(@"%@", [arr2 filteredArrayUsingPredicate:predicate]);
    // 取出arr1 & arr2 都包含的元素
    predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", arr1];
    NSLog(@"%@", [arr2 filteredArrayUsingPredicate:predicate]);
    // 取出arr1中  arr2 & arr1都不包含的元素
    predicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)", arr2];
    NSLog(@"%@", [arr1 filteredArrayUsingPredicate:predicate]);
    
    // array[index]:返回array数组中index索引处的元素
    // array[FIRST]:返回array数组中第一个元素
    // array[LAST]:返回array数组中最后一个元素
    // array[SIZE]:返回array数组中元素的个数
}
上一篇 下一篇

猜你喜欢

热点阅读