上一篇是講怎麼進行CoreData的基本操做,這一篇是講NSFetchedResultsController獲得CoreData數據怎麼與tableView完美結合,和動畫操做的實現。git
NSFetchedResultsController的結果與tableView的結合github
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [[self.queryData sections] count]; } - (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section { if ([[self.queryData sections] count] > 0) { id <NSFetchedResultsSectionInfo> sectionInfo = [[self.queryData sections] objectAtIndex:section]; return [sectionInfo numberOfObjects]; } else return 0; }
NSFetchedResultsControllerDelegate代理方法的實現fetch
CoreData中數據將要改變調用的方法動畫
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { // The fetch controller is about to start sending change notifications, so prepare the table view for updates. [self.tableView beginUpdates]; }
CoreData中行數據改變調用的方法能夠在數據改變時實現某些動畫spa
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { UITableView *tableView = self.tableView; switch(type) { case NSFetchedResultsChangeInsert: [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationRight]; break; case NSFetchedResultsChangeDelete: [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom]; break; case NSFetchedResultsChangeUpdate: [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; break; case NSFetchedResultsChangeMove: [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; break; } }
CoreData中組的數據改變時調用的方法也能夠實現某些動畫代理
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { switch(type) { case NSFetchedResultsChangeInsert: [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic]; break; case NSFetchedResultsChangeMove: break; case NSFetchedResultsChangeUpdate: break; case NSFetchedResultsChangeDelete: [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic]; break; } }
CoreData中的數據已經改變時調用的方法blog
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { self.dataList = self.queryData.fetchedObjects.mutableCopy; NSLog(@"%@",self.dataList); [self.tableView endUpdates]; }
本文GitHub地址https://github.com/zhangkiwi/iOS_SN_CoreDataget