Skip to content

Instantly share code, notes, and snippets.

@chbeer
Created October 25, 2011 14:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chbeer/1312967 to your computer and use it in GitHub Desktop.
Save chbeer/1312967 to your computer and use it in GitHub Desktop.
performFetchAndUpdateTableView: that performs a fetch request on NSFetchedResultsController and updates table view
// ONLY WORKS WITH ONE SECTION!!
- (BOOL) performFetchAndUpdateTableView:(NSError **)error
{
NSArray *objectsBefore = [self.fetchedResultsController.fetchedObjects retain];
BOOL result = [self.fetchedResultsController performFetch:error];
if (result) {
NSArray *objectsAfter = self.fetchedResultsController.fetchedObjects;
NSMutableArray *insertedObjects = [[objectsAfter mutableCopy] autorelease];
[insertedObjects removeObjectsInArray:objectsBefore];
NSMutableArray *removedObjects = [[objectsBefore mutableCopy] autorelease];
[removedObjects removeObjectsInArray:objectsAfter];
NSMutableArray *insertedIndexPaths = [NSMutableArray arrayWithCapacity:insertedObjects.count];
[insertedObjects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[insertedIndexPaths addObject:[NSIndexPath indexPathForRow:[objectsAfter indexOfObject:obj] inSection:0]];
}];
NSMutableArray *removedIndexPaths = [NSMutableArray arrayWithCapacity:removedObjects.count];
[removedObjects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[removedIndexPaths addObject:[NSIndexPath indexPathForRow:[objectsBefore indexOfObject:obj] inSection:0]];
}];
if (insertedIndexPaths.count > 0 || removedIndexPaths.count > 0) {
[_tableView beginUpdates];
[_tableView insertRowsAtIndexPaths:insertedIndexPaths
withRowAnimation:UITableViewRowAnimationFade];
[_tableView deleteRowsAtIndexPaths:removedIndexPaths
withRowAnimation:UITableViewRowAnimationFade];
[_tableView endUpdates];
}
}
[objectsBefore release];
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment