NSArray *testArray = @[@1, @2, @3, @4, @5, @6];
// AND、&&:逻辑与,要求两个表达式的值都为YES时,结果才为YES。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF > 2 && SELF < 5"];
NSArray *filterArray = [testArray filteredArrayUsingPredicate:predicate];
NSLog(@"元素值大于2,且小于5的数组:%@", filterArray);
// OR、||:逻辑或,要求其中一个表达式为YES时,结果就是YES
predicate = [NSPredicate predicateWithFormat:@"SELF < 2 || SELF > 5"];
filterArray = [testArray filteredArrayUsingPredicate:predicate];
NSLog(@"元素值小于2,或大于5的数组:%@", filterArray);
// NOT、 !:逻辑非,对原有的表达式取反
predicate = [NSPredicate predicateWithFormat:@"NOT (SELF > 2 AND SELF < 5)"];
filterArray = [testArray filteredArrayUsingPredicate:predicate];
NSLog(@"元素值既不大于2也不小于5,即小于等于2,或大于等于5:%@", filterArray);
运行结果
2018-03-05 15:32:44.268 DemoNSPredicate[2472:315182] 元素值大于2,且小于5的数组:(
3,
4
)
2018-03-05 15:32:44.268 DemoNSPredicate[2472:315182] 元素值小于2,或大于5的数组:(
1,
6
)
2018-03-05 15:32:44.269 DemoNSPredicate[2472:315182] 元素值既不大于2也不小于5,即小于等于2,或大于等于5:(
1,
2,
5,
6
)
2018-03-05 15:32:44.269 DemoNSPredicate[2472:315182] 元素值大于5的数组:(
6
)