NSFetchRequestController :将tableVIew单元格与数据内容绑定,响应数据变化
1.变量声明
var myClassInfo :[Class]?
var tableView:UITableView!
var fController:NSFetchedResultsController<Class>!
2.在viewdidLoad中添加
let request:NSFetchRequest<Class> = Class.fetchRequest()
//如何排序
let sort:NSSortDescriptor = NSSortDescriptor(key: "stuID", ascending: true)
request.sortDescriptors = [sort]
// 获取上下文
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
// 初始化控制器,指定代理
fController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fController.delegate = self
//执行获取数据,并赋给数组
do {
try fController.performFetch()
if let object = fController.fetchedObjects{
myClassInfo = object
}
} catch {
print(error)
}
3.代理实现
//数据内容发生变化时,NSFetchedResultsControllerDelegate的协议会被调用
//当控制器开始处理内容变化时
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
//内容发生变更时
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
//变更类型
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .automatic)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .automatic)
case .update:
tableView.reloadRows(at: [indexPath!], with: .automatic)
default:
tableView.reloadData()
}
//同步到数组
if let object = controller.fetchedObjects{
myClassInfo = object as? [Class]
}
}
//当控制器已经处理完内容变更时
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>){
tableView.endUpdates()
}
4. 删除操作
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.delete
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(self.fController.object(at: indexPath))
appDelegate.saveContext()
}
override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String?{
return "删除"
}