NSPredicate用于对集合类中的元素进行筛选

 

#import <Foundation/Foundation.h>

#import "Person.h"

 

#define PRINT_BOOL(X) NSLog(@#X" %@", (X) ? @"是" : @"否")

 

int main(int argc, const char * argv[]) {

    NSPredicate *predicate = nil;

    NSString *s = nil;

    

    Person *person = [[Person alloc] init];

    person.name = @"张三";

    person.age = 22;

 

    // 基本的匹配比较1,比较这个person的age是否大于20

    predicate = [NSPredicate predicateWithFormat:@"age > 20"];

    BOOL isMatch1 = [predicate evaluateWithObject:person];

    PRINT_BOOL(isMatch1);

    

    // 基本的匹配比较2,比较s这个字符串是否等于“Hello”

    s = @"Hello";

    predicate = [NSPredicate predicateWithFormat:@"SELF == 'Hello'"];

    BOOL isMatch2 = [predicate evaluateWithObject:s];

    PRINT_BOOL(isMatch2);

    

    // 带参数的匹配比较1(不能将参数作为属性路径),varDict的Key“name”对应的Value是不是以‘张’开头

    predicate = [NSPredicate predicateWithFormat:@"name LIKE $NAME"];

    NSDictionary *varDict = @{@"NAME":@"张*"};

    predicate = [predicate predicateWithSubstitutionVariables:varDict];

    BOOL isMatch3 = [predicate evaluateWithObject:person];

    PRINT_BOOL(isMatch3);

 

    // 带参数的匹配比较(%K代表路径,%@代表值)

    predicate = [NSPredicate predicateWithFormat:@"%K == %@", @"name", @"张三1"];

    BOOL isMatch4 = [predicate evaluateWithObject:person];

    PRINT_BOOL(isMatch4);

    

    // NSArray筛选数组里面大于5的对象

    NSArray *arr = @[@1, @3, @8, @5, @6, @7];

    predicate = [NSPredicate predicateWithFormat:@"SELF > 5"];

    NSArray *arrRet = [arr filteredArrayUsingPredicate:predicate];

    NSLog(@"%@", arrRet);

    

    // NSMutableArray筛选包含‘en’的对象

    NSArray *arr1 = @[@"Chengdu", @"Beijing", @"Shanghai"];

    NSMutableArray *arr2 = [NSMutableArray arrayWithArray:arr1];

    predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS 'en'"];

    [arr2 filterUsingPredicate:predicate];

    NSLog(@"%@", arr2);

 

    [predicate release];

    [person release];

    

    return 0;

}

原文地址:https://www.cnblogs.com/tang910103/p/5061489.html