Predicate

NSCompoundPredicate的使用

2020-09-09  本文已影响0人  想聽丿伱說衹愛我

版本:iOS13.7

一、简介

NSCompoundPredicate是复合谓词,通过多个谓词进行AND、OR、NOT组合来评估对象。
NSCompoundPredicate是NSPredicate的子类,点击NSPredicate的使用查看NSPredicate的用法,以便更容易理解NSCompoundPredicate。

二、NSCompoundPredicate的API

@interface NSCompoundPredicate : NSPredicate

//通过多个谓词创建一个复合谓词
//type 复合类型 详见说明1
//subpredicates 谓词数组
- (instancetype)initWithType:(NSCompoundPredicateType)type 
                subpredicates:(NSArray<NSPredicate *> *)subpredicates;
//初始化方法,一般使用上面的方法
- (nullable instancetype)initWithCoder:(NSCoder *)coder;

//复合类型 只读 详见说明1
@property (readonly) NSCompoundPredicateType compoundPredicateType;
//复合谓词的谓词数组 只读
@property (readonly, copy) NSArray *subpredicates;

//简易复合谓词的初始化方法 此时NSCompoundPredicateType为NSAndPredicateType
//相当于[[NSCompoundPredicate alloc] initWithType:NSAndPredicateType subpredicates:subpredicates]
+ (NSCompoundPredicate *)andPredicateWithSubpredicates:(NSArray<NSPredicate *> *)subpredicates;
//简易复合谓词的初始化方法 此时NSCompoundPredicateType为NSOrPredicateType
+ (NSCompoundPredicate *)orPredicateWithSubpredicates:(NSArray<NSPredicate *> *)subpredicates;
//简易复合谓词的初始化方法 此时NSCompoundPredicateType为NSNotPredicateType
+ (NSCompoundPredicate *)notPredicateWithSubpredicate:(NSPredicate *)predicate;

@end
typedef NS_ENUM(NSUInteger, NSCompoundPredicateType) {
    //给单个谓词表达式添加NOT,SELF CONTAINS 'string'变成NOT SELF CONTAINS 'string'
    NSNotPredicateType = 0, 
    //多个谓词表达式之间添加AND
    NSAndPredicateType,
    //多个谓词表达式之间添加OR
    NSOrPredicateType,
};

三、应用

    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF > 10"];
    NSLog(@"predicate1 = %@", [predicate1 predicateFormat]);
    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"SELF < 50"];
    NSLog(@"predicate2 = %@", [predicate2 predicateFormat]);
    NSCompoundPredicate *compound = [[NSCompoundPredicate alloc] initWithType:NSAndPredicateType 
                                      subpredicates:@[predicate1, predicate2]];
    NSLog(@"compound = %@", [compound predicateFormat]);
    success = [compound evaluateWithObject:@20];
    NSLog(@"%@", @(success));
输出:
predicate1 = SELF > 10
predicate2 = SELF < 50
compound = SELF > 10 AND SELF < 50
1

将两个谓词组合起来,最终复合谓词表达式变成SELF > 10 AND SELF < 50

上一篇下一篇

猜你喜欢

热点阅读