用来管理查询结果的控制器,特别适合tableview显示数据以及修改数据。
1) 实例化查询请求对象
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
2) 实例化排序对象
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
3) 设置请求的排序
fetchRequest.sortDescriptors = @[sort];
4)实例化查询结果控制器(指定请求对象, 上下文, section在属性的哪个Key)
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext: Context sectionNameKeyPath:@"section" cacheName:nil];
5)执行查询
NSError *error = nil;
[_fetchedResultsController performFetch:&error];
NSLog(@"%@",error);
6) 查询完的结果会在这里(一个模型对象数组--实例化请求时指定的实体名类型的对象)
_fetchedResultsController.fetchedObjects
拥有增删改查的代理方法
控制器里的模型对象发生改变类型(插入/移动/删除)时调用,会告诉你之前和之后的索引,
controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:
对象模型section改变时调用
controller:didChangeSection:atIndex:forChangeType:
找我要分组名sectionName
controller:sectionIndexTitleForSectionName:
控制器里的模型对象已经发生改变时调用
controllerDidChangeContent:
控制器里的模型对象即将发生改变时调用
controllerWillChangeContent:
配对tableView的一些方法
1.section数组
self.fetchedResultsController.sections
2.根据索引取出对象
[self.fetchedResultsController objectAtIndexPath:indexPath]
3.section的indexTitle数组
self.fetchedResultsController.sectionIndexTitles