接着上一篇,直接上查询代码。
//查询数据
- (IBAction)chaXunAction:(UIButton *)sender {
//第一步:创建一个FetchRequest对象-表示一个用来从数据持久库中检索数据的检索标准。
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//第二步:创建一个实体描述类实例--根据数据库表名
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:_appDelegate.managedObjectContext];
//把这个实体描述实例 加到这个检索标准中。
[fetchRequest setEntity:entity];
//当没有条件查询的时候,这几行语句直接不加就可以了。
// //指定取对象的一个过滤标准--其实就是条件查询,也叫谓词检索。
// // Specify criteria for filtering which objects to fetch
// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"", @""];
// //把这个检索条件加到检索标准中。
// [fetchRequest setPredicate:predicate];
//指定对取来的对象的分类标准
// Specify how the fetched objects should be sorted
//比如这里,根据age排序
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age"
ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
NSError *error = nil;
//最终根据检索标准检索到的对象。
NSArray *fetchedObjects = [_appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
//判断检索来的对象是否为空。
if (fetchedObjects == nil) {
NSLog(@"error: %@",error);
}
//校验使用
for (Student *result in fetchedObjects) {
NSLog(@"哈哈 name: %@, age: %@, gender: %@, address: %@",result.name,result.age,result.gender,result.address);
}
}
就这样,就完成了数据的检索。