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