關於Core Data的一些整理(五)

關於Core Data的一些整理(五)

在Core Data中使用NSFetchedResultsController(如下簡稱VC)實現與TableView的交互,在實際中,使用VC有不少優勢,其中最主要的是下面三點:緩存

  1. Sections,你能夠使用關鍵字將大量數據分隔成一段段的Section,在使用TableView時設置headerTitle時尤其好用
  2. Caching,在初始化VC時設置Caching名字便可使用,能夠大量節約時間
  3. 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 }
相關文章
相關標籤/搜索