首先创建一个NSFetchedResultsController
var fetchedResultsVC : NSFetchedResultsController!
var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
再创建一个空命令
let fetchRequest = NSFetchRequest(entityName: "Item")
创建数组排序,按照key值升序或者降序排列
let sortDesctiptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDesctiptor]
创建NSFetchedResultsController
fetchedResultsVC = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: appDelegate.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
添加NSFetchedResultsController的协议(NSFetchedResultsControllerDelegate)
fetchedResultsVC.delegate = self
执行
do {
try fetchedResultsVC.performFetch()
}catch let error{
print(error)
}
由于目前能力有限,还不清楚如何使得添加数据时保持section不划分,So,添加如下以免报错:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return (fetchedResultsVC.sections?.count)!
}
NSFetchedResultsControllerDelegate遵循的方法
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView!.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView!.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView!.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
let cell = tableView!.cellForRowAtIndexPath(indexPath!)
let model = fetchedResultsVC.objectAtIndexPath(indexPath!) as? Item
cell!.textLabel?.text = model!.name
cell!.detailTextLabel?.text = "\(model!.score)"
case .Move:
tableView!.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
tableView!.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView!.endUpdates()
}
完了。
但是在didChangeObject这个方法中case .Move:之前没有写的时候,添加数据时tableView没有刷新,但是添加了case .Move:和里面的方法以后数据就正常了,我也不知道是不是xcode抽风了。