美文网首页
Swift CoreData&NSFetchResultCon

Swift CoreData&NSFetchResultCon

作者: 翔战士 | 来源:发表于2017-11-18 15:57 被阅读0次

    一.向数据库中存储数据


    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)")

                    }    

        }

    相关文章

      网友评论

          本文标题:Swift CoreData&NSFetchResultCon

          本文链接:https://www.haomeiwen.com/subject/hdwevxtx.html