一.向数据库中存储数据
1.顶部头文件导入CoreData
2.自定义存储函数
二.获取数据库数据(应用NSFetchResultController)
1.顶部头文件导入CoreData
2.定义NSFetchResultController控制器的局部变量:
var fetchResultController: NSFetchResultController<"此处填写实例对象的名称">!
3.初始化NSFetchResultController
func initFetchResultController() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
// data内的排序方式
let fetchRequest = NSFetchRequest(entityName: "Area")
let sd = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sd] fetchResultController =
NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fetchResultController.delegate = self
do {
try fetchResultController.performFetch()
if let objects = fetchResultController.fetchedObjects {
areas = objects
}
} catch {
print("无法取到数据库\(error)")
}
}
3.设置界面自动根据响应改变
func controllerWillChangeContent(_ controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController) {
tableView.endUpdates()
}
func controller(_ controller: NSFetchedResultsController, 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()
}
do {
try fetchResultController.performFetch()
if let objects = fetchResultController.fetchedObjects {
areas = objects
}
} catch {
print("错误为:\(error)")
}
}
网友评论