一.向數(shù)據(jù)庫中存儲數(shù)據(jù)
1.頂部頭文件導入CoreData
2.自定義存儲函數(shù)
二.獲取數(shù)據(jù)庫數(shù)據(jù)(應(yīng)用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內(nèi)的排序方式?
?????????????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("無法取到數(shù)據(jù)庫\(error)")?
?????????????????}
? ? ? ? ? ? }
3.設(shè)置界面自動根據(jù)響應(yīng)改變
????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)")
????????????????}????
????}