美文网首页Coredata
CoreData的使用(三)--UITableView

CoreData的使用(三)--UITableView

作者: StoneWing | 来源:发表于2017-06-19 10:32 被阅读232次

    在我们正常的项目中使用,简单的增删改查,当然可以实现大多数的功能,但是有的实现的话相对可能复杂一些,比如保存的数据改变了我们要刷新tableview的数据。这里coredata中提供了一个NSFetchedResultsController类来和tableview一起使用,下面我们看一下如何使用NSFetchedResultsController和tableview

    • 新建NSFetchedResultsController,并进行初始化

      这里需要提一下的是,sort排序是必须添加的,否则运行后报错

    var controller: NSFetchedResultsController<DemoModel>!

    func initController() {

        let request: NSFetchRequest<DemoModel> = DemoModel.fetchRequest()
        
        //条件查询
        let predicate: NSPredicate = NSPredicate(format: "id == %@", "1")
        request.predicate = predicate
        
        //排序
        let sort = NSSortDescriptor(key: "id", ascending: false)
        request.sortDescriptors = [sort]
        
        //sectionNameKeyPath为section的title对应的key,nil的话代表只有一个section
        controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: CONTEXT, sectionNameKeyPath: "title", cacheName: nil)
        controller.delegate = self
        
        do {
            try controller.performFetch()
        }catch {
            print("获取数据失败")
        }
        
    }
    
    * ### 实现NSFetchedResultsControllerDelegate,当coredata中的数据发生改变的时候调用
    * ##### controllerDidChangeContent只使用这个方法,当数据改变完成后调用,直接刷新tableview的数据
    ```swift
    /// 当coredata存储的数据改变后调用的方法,这里直接更新tableview
      ///
      /// - Parameter controller: <#controller description#>
      func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
          self.tableView.reloadData()
      }
    
    • 当然也可以添加一些刷新动画,或者不需要等数据改变完成后才更新ui的设置
    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
            self.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: .left)
                break
            case .delete:
                tableView.deleteRows(at: [indexPath!], with: .right)
                break
            case .update:
                self.configureCell(cell: tableView.dequeueReusableCell(withIdentifier: identifier), indexPath: indexPath)
                break
            case .move:
                tableView.deleteRows(at: [indexPath!], with: .none)
                tableView.reloadSections([newIndexPath?.section], with: .none)
                break
            }
        }
        
        /// 当coredata存储的数据改变后调用的方法,这里直接更新tableview
        ///
        /// - Parameter controller: <#controller description#>
        func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
            self.tableView.endUpdates()()
        }
    
    • 实现UITableView的datasource,进行数据绑定,这里只写出了和coredata相关的方法

    extension ViewController: UITableViewDataSource {
        
        func numberOfSections(in tableView: UITableView) -> Int {
            return self.controller.sections!.count
        }
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.controller.sections![section].numberOfObjects
        }
        
        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            return self.controller.sections![section].name
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
            //coreData的数据模型的获取
            let model = self.controller.object(at: indexPath)
            ...
        }
    }
    

    上一节:CoreData的使用(二)---增删改查

    相关文章

      网友评论

        本文标题:CoreData的使用(三)--UITableView

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