Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wanbok/86009cf22646fb89c79d to your computer and use it in GitHub Desktop.
Save wanbok/86009cf22646fb89c79d to your computer and use it in GitHub Desktop.
Implement NSFetchedResultsControllerDelegate for UICollectionViewController. Refered this : http://samwize.com/2014/07/07/implementing-nsfetchedresultscontroller-for-uicollectionview/
class CollectionViewController: UICollectionViewController {
var sectionChanges: [[NSFetchedResultsChangeType: Int]]? = nil
var itemChanges: [[NSFetchedResultsChangeType: AnyObject]]? = nil
...
}
// MARK: NSFetchedResultsControllerDelegate
extension CollectionViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(controller: NSFetchedResultsController) {
sectionChanges = [[NSFetchedResultsChangeType: Int]]()
itemChanges = [[NSFetchedResultsChangeType: AnyObject]]()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
sectionChanges?.append([type: sectionIndex])
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case NSFetchedResultsChangeType.Insert:
itemChanges?.append([type: newIndexPath!])
case NSFetchedResultsChangeType.Delete, NSFetchedResultsChangeType.Update:
itemChanges?.append([type: indexPath!])
case NSFetchedResultsChangeType.Move:
itemChanges?.append([type: [indexPath!, newIndexPath!]])
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
collectionView?.performBatchUpdates({ () in
for dic in self.sectionChanges! {
for (type, sectionIndex) in dic {
switch type {
case NSFetchedResultsChangeType.Insert:
self.collectionView?.insertSections(NSIndexSet(index: sectionIndex))
case NSFetchedResultsChangeType.Delete:
self.collectionView?.deleteSections(NSIndexSet(index: sectionIndex))
default:
break
}
}
}
for dic in self.itemChanges! {
for (type, item) in dic {
switch type {
case NSFetchedResultsChangeType.Insert:
self.collectionView?.insertItemsAtIndexPaths([item])
case NSFetchedResultsChangeType.Delete:
self.collectionView?.deleteItemsAtIndexPaths([item])
case NSFetchedResultsChangeType.Update:
self.collectionView?.reloadItemsAtIndexPaths([item])
case NSFetchedResultsChangeType.Move:
let items = item as [NSIndexPath]
self.collectionView?.moveItemAtIndexPath(items[0], toIndexPath: items[1])
default:
break
}
}
}
}, completion: {(finished) -> Void in
self.sectionChanges = nil
self.itemChanges = nil
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment