OC中的谓词

谓词是 OC 中提供了的针对数组处理的。它的作用和数据库中的查询操作很像。只是针对的对象是数组。这样我们可以通过简单的谓词语句进行对数组进行查找和过滤。
具体怎么操作下面通过代码看一下。

// 创建一个Person类型, 有 age 和 name 两个属性
// Person.h
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSUInteger age;
@end

// 假如我们有一个数组是存放Person对象的

  NSMutableArray *array = [NSMutableArray array];
        
        for (int i = 0; i < 20; i++) {
            Person *person = [[Person alloc] init];
            if (i < 5) {
                person.name = [NSString stringWithFormat:@"dz-%d", i];
            } else {
                person.name = [NSString stringWithFormat:@"wy-%d", i];
            }
            person.age = 20 + i;
            [array addObject:person];
        }

那么我们看看如何进行操作

1>进行过滤。
什么是过滤呢?苹果有两个方法可以使用的,分别对array 和 mutableArray 进行操作

// 这个方法是针对可变数组操作的,直接将不满足条件的删掉
- (void)filterUsingPredicate:(NSPredicate *)predicate;
// 这个方法针对数组,将过滤的结果返回给一个新的数组
- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate; 

举个栗子

// 创建一个过滤条件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < 23"];
// 进行过滤
NSArray *filterArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%d", filterArray.count);

上面提到创建一个过滤条件。但是条件如何去写呢。他有几个关键字
我们可以看一下
它支持常用的判断条件 OR, AND, BEGINSWICH, ENDSWITH, IN, CONTAINS, LIKE,
当然也可以使用占位符
例如:

// OR, AND 应该很熟悉
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" name='dz-8' OR age < %d AND age > %d", 25, 21];

// IN 从数组里面判断
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" name IN {'dz-9', 'wy-5'} ];

// BEGINSWICH 以xxx开头, ENDSWITH 以xxx结尾
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" name BEGINSWITH 'd' "} ];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@" name ENDSWITH '9' "} ];

// CONTAINS 包含 只要包含就可以
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name Like 'z'"];

// LIKE 模糊查找  *代表模糊的字符
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name Like '*z*'"];

2

你可能感兴趣的:(OC中的谓词)