过滤数组中的字符串
NSArray *arr = @[@"hello",@"world",@"wellcome"];
//创建一个谓词,谓词的逻辑是被过滤的主体是以'h'开头 的字符串
//self 代表对象自身, like为指定搜索模式, '*'为通配符
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self like h*"];
predicate = [NSPredicate predicateWithFormat:@"self beginswith 'h'"];
//筛选以'd'结尾
predicate = [NSPredicate predicateWithFormat:@"self endswith 'd'"];
predicate = [NSPredicate predicateWithFormat:@"self like '*d'"];
//将数组中所有满足条件的筛选出来, 生成新的数组
NSArray *result = [arr filteredArrayUsingPredicate:predicate];
//筛选含有'h'的单词
//[c]指定不区分大小写
predicate = [NSPredicate predicateWithFormat:@"self contains[c] 'h'"];
predicate = [NSPredicate predicateWithFormat:@"self like *h*"];
判断对象是否符合某种条件
NSString *demoStr = @"hello world!!";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self like h*"];
BOOL isBeginWith_h = [predicate evaluateWithObject:demoStr];
过滤自定义对象的实例变量符合某种条件
Person *person1 = [[Person alloc] initWithName:@"张三" andAge:21];
Person *person2 = [[Person alloc] initWithName:@"李四" andAge:22];
Person *person3 = [[Person alloc] initWithName:@"王五" andAge:23];
Person *person4 = [[Person alloc] initWithName:@"赵六" andAge:24];
NSArray *arr = @[person1,person2,person3,person4];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains '三'"];
NSArray *result = [arr filteredArrayUsingPredicate:predicate];
for (Person *tmp in result) {
NSLog(@"---------->%@:%ld",tmp.name,tmp.age);
}
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"age >= 22 && age < 24"];
result = [arr filteredArrayUsingPredicate:predicate2];
for (Person *tmp in result) {
NSLog(@"----->%@:%ld",tmp.name,tmp.age);
}
匹配正则表达式
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self matches %@", @"正则表达式"];