@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *per1 = [Person personWithName:@"AA" age:20];
Person *per2 = [Person personWithName:@"DD" age:25];
Person *per3 = [Person personWithName:@"GG" age:92];
Person *per4 = [Person personWithName:@"KK" age:38];
Person *per5 = [Person personWithName:@"12138" age:12138];
Person *per6 = [Person personWithName:@"斯娜格" age:81];
Person *per7 = [Person personWithName:@"gakki" age:18];
Person *per8 = [Person personWithName:@"康东" age:46];
Person *per9 = [Person personWithName:@"maky3x" age:67];
Person *per0 = [Person personWithName:@"3rt" age:55];
NSArray *persons = [NSArray arrayWithObjects:per0, per1, per2, per3, per4, per5, per6, per7, per8, per9, nil];
//1 年龄小于30
//定义谓词对象,谓词对象中包含了过滤条件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < 30"];
//使用谓词条件过滤数组中的元素,过滤之后返回查询的结果
NSArray *array = [persons filteredArrayUsingPredic
ate:predicate];
for (Person *per in array) {
NSLog(@"1 age < 30 --> %@, %ld", per.name, per.age);
}
//2 年龄小于30并且名字为gakki的
predicate = [NSPredicate predicateWithFormat:@"name = 'gakki' && age < 30"];
array = [persons filteredArrayUsingPredic
ate:predicate];
for (Person *per in array) {
NSLog(@"2 age < 30 && name = gakki --> %@, %ld", per.name, per.age);
}
//3 in (包含)
predicate = [NSPredicate predicateWithFormat:@"name IN {'AA', 'D'} "];
array = [persons filteredArrayUsingPredic
ate:predicate];
NSLog(@"%ld", array.count);
for (Person *per in array) {
NSLog(@"3 %@, %ld", per.name, per.age);
}
//4 name以m开头的
predicate = [NSPredicate predicateWithFormat:@"name beginswith 'm' "];
array = [persons filteredArrayUsingPredic
ate:predicate];
NSLog(@"%ld", array.count);
for (Person *per in array) {
NSLog(@"4 %@, %ld", per.name, per.age);
}
//5 name以38结尾的
predicate = [NSPredicate predicateWithFormat:@"name endswith '38'"];
array = [persons filteredArrayUsingPredic
ate:predicate];
NSLog(@"%ld", array.count);
for (Person *per in array) {
NSLog(@"5 %@, %ld", per.name, per.age);
}
//6 name中包含3x的
predicate = [NSPredicate predicateWithFormat:@"name contains '3x'"];
array = [persons filteredArrayUsingPredic
ate:predicate];
NSLog(@"%ld", array.count);
for (Person *per in array) {
NSLog(@"6 %@, %ld", per.name, per.age);
}
//7 name中包含
?表示一个字符
*表示0个或多个字符
//predicate = [NSPredicate predicateWithFormat:@"name like '*3?'"];
//predicate = [NSPredicate predicateWithFormat:@"name like '?a*'"];
predicate = [NSPredicate predicateWithFormat:@"name like '*3*'"];
array = [persons filteredArrayUsingPredic
ate:predicate];
NSLog(@"%ld", array.count);
for (Person *per in array) {
NSLog(@"7 %@, %ld", per.name, per.age);
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
@end
@implementation ViewController
- (void)viewDidLoad {
}
- (void)didReceiveMemoryWarning {
}
@end