1 在数组中的使用
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSArray* intAttr = @[
@1,@100,@44,@60
];
//可以直接写条件(过滤大于40的元素)
NSArray* result1 = [intAttr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF > 40"]];
NSLog(@"过滤结果为:%d",result1.count);
//也可以写占位符,后面补充占位符的值(过滤大于四十的元素)
NSArray* result2 = [intAttr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF > %d",40]];
NSLog(@"过滤结果为:%d",result2.count);
//过滤元素中name字段包含大王的元素
[NSPredicate predicateWithFormat:@"name CONTAINS '大王'"];
NSArray* users = @[
[[FKUser alloc] initWithName:@"gy1" pass:@"1"],
[[FKUser alloc] initWithName:@"gy1" pass:@"1"],
[[FKUser alloc] initWithName:@"gy2" pass:@"1"],
[[FKUser alloc] initWithName:@"gy3" pass:@"1"],
];
//%k 可以指定元素的属性 比如这里指定的是 FKUser的name 属性 包含1
NSPredicate* predicate1 = [NSPredicate predicateWithFormat:@"%K CONTAINS %@",@"name",@"1"];
NSArray* user1 = [users filteredArrayUsingPredicate:predicate1];
NSLog(@"===过滤结果为:%d",user1.count);
//%K还是指定属性值,只是$SUBSTR 不需要直接指定
NSPredicate* predicate2 = [NSPredicate predicateWithFormat:@"%K CONTAINS $SUBSTR",@"name"];
//指定$SUBSTR 生成新的谓语
NSPredicate* realPredicate2 = [predicate2 predicateWithSubstitutionVariables:@{@"SUBSTR":@"1"}];
//使用谓语过滤数组
NSArray* user3 = [users filteredArrayUsingPredicate:realPredicate2];
NSLog(@"3=====过滤结果为:%d",user3.count);
NSPredicate* predicate3 = [NSPredicate predicateWithFormat:@"%K CONTAINS $SUBSTR",@"name"];
NSPredicate* realPredicate3 = [predicate3 predicateWithSubstitutionVariables:@{@"SUBSTR":@"2"}];
NSArray* user4 = [users filteredArrayUsingPredicate:realPredicate3];
NSLog(@"4=====过滤结果为:%d",user4.count);
}
return 0;
}