版本:iOS13.7
一、簡介
NSCompoundPredicate是復合謂詞程腹,通過多個謂詞進行AND匣吊、OR、NOT組合來評估對象寸潦。
NSCompoundPredicate是NSPredicate的子類色鸳,點擊NSPredicate的使用查看NSPredicate的用法,以便更容易理解NSCompoundPredicate见转。
二命雀、NSCompoundPredicate的API
@interface NSCompoundPredicate : NSPredicate
//通過多個謂詞創(chuàng)建一個復合謂詞
//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
- 說明1
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