iOS_SN_CoreData(二)

时间:2024-08-11 10:04:02

上一篇是讲怎么进行CoreData的基本操作,这一篇是讲NSFetchedResultsController得到CoreData数据怎么与tableView完美结合,和动画操作的实现。

NSFetchedResultsController的结果与tableView的结合

- (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代理方法的实现

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中行数据改变调用的方法可以在数据改变时实现某些动画

- (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中的数据已经改变时调用的方法

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
self.dataList = self.queryData.fetchedObjects.mutableCopy;
NSLog(@"%@",self.dataList);
[self.tableView endUpdates];
}

  

本文GitHub地址https://github.com/zhangkiwi/iOS_SN_CoreData