- (IBAction)searchClick:(id)sender {
//1. 创建查询请求
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//2. 创建实体描述 --> 表名
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:HMManagerContext];
[fetchRequest setEntity:entity];
//3. 谓词 --> 查询条件
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"height>175"];
// [fetchRequest setPredicate:predicate];
//4. 排序描述 --> 可以增加多个
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"position" ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor,sortDescriptor2, nil]];
//5. 执行查询请求
NSError *error = nil;
NSArray *fetchedObjects = [HMManagerContext executeFetchRequest:fetchRequest error:&error];
//6. 未查询到数据
if (fetchedObjects == nil) {
NSLog(@"error: %@", error);
return;
}
for (Person *p in fetchedObjects) {
NSLog(@"Person: %@, %@, %zd, %zd", p.name, p.position, p.age, p.height);
}
}