关于Core Data的一些整理(五)
在Core Data中使用NSFetchedResultsController
(以下简称VC)实现与TableView的交互,在实际中,使用VC有很多优点,其中最主要的是下面三点:
- Sections,你可以使用关键字将大量数据分隔成一段段的Section,在使用TableView时设置headerTitle时尤为好用
- Caching,在初始化VC时设置Caching名字即可使用,可以大量节约时间
- NSFetchedResultsControllerDelegate,监控数据的变动
//首先是VC的初始化如下
//生成fetch请求
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Team"];
//添加排序方式
NSSortDescriptor *zoneSort = [NSSortDescriptor sortDescriptorWithKey:@"qualifyingZone" ascending:YES];
NSSortDescriptor *scoresort = [NSSortDescriptor sortDescriptorWithKey:@"wins" ascending:NO];
NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:@"teamName" ascending:YES];
fetchRequest.sortDescriptors = @[zoneSort, scoresort, nameSort];
//初始化NSFetchedResultsController,并以qualifyingZone来分为N个section,添加名为worldCup的缓存
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.coreDataStack.context sectionNameKeyPath:@"qualifyingZone" cacheName:@"worldCup"];
self.fetchedResultsController.delegate = self;
[self.fetchedResultsController performFetch:nil]; //下面是VC协议的实现,如第一个函数所见,VC与tableView有相对应的处理类型:Insert、Delete、Update、Move
#pragma mark - NSFetchedResultsControllerDelegate
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
TeamCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
switch (type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:cell withIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
default:
break;
}
}
//需要注意的一点是,要有下面对tableView的更新方法,否则会报错
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[self.tableView beginUpdates];
} - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
}