CoreData NSFetchedResultsController 简介

文章参考 Core_Data_by_Tutorials_v2.0 翻译 代码是基于 Swift2.0

NSFetchedResultsController一个控制器,但是他不是视图控制器哦。它可以很方便的驱动 UITableView

通常我们会使用一个数组来用作tableview的数据源,但这种做法的关键问题在于:假如数组特别大,而占用的内存又特别多的话,那么程序性能将受到严重的影响,这点在原来的开发中可能已经体会到了。但在早些时候,我们通过NSFetchRequest获取CoreData数据,但这种做法返回的仍然是一个数组。虽然说,我们可以直接使用这种数组来填充数据,不过这次额外配置一些选项。比方说,可以通过设定setFetchBatchSize选项来分批获取数据。这一选项虽小,但他对内存用量的影响却很大,而且还能因此改善整个程序的性能

想在CoreData 与表格视图之间高效地管理获取到的数据,最好的方式就是使用 NSFetchedResultsController 。假如直接使用由 NSFetchRequest 所返回的数组,而不是用NSFetchResultsController,那么当底层数据有变化时,数组里的对象可能就会失效,而应用程序也可能就会随之崩溃。

把表格视图设置为 NSFetchResultsController 的委托,可以使表格视图具备追踪数据变更的能力,也就是说,假如获取到的对象在底层的上下文中发生了变化,那么表格视图亦将随之自动更新。由NSFetchedResultsController所支援的表格视图其效率也可以通过设置缓存而提升,开发者只需要给缓存取个独特的名字即可。用了缓存之后,就可以尽量减少那种无谓的重复获取操作了。除了可以提升性能及追踪数据变更之外,NSFetchedResultsController 还具备一些非常方便的特性,开发者可以用它们来轻松的配置由CoreData所驱动的表格视图。

项目初始化下载

It all begins with a fetch request...

在上边给出的链接中下载我们所要使用到的初始项目。

打开我们的ViewController.swift 文件添加下边的代码

import CoreData
============
var fetchedResultsController: NSFetchedResultsController!

接下里在viewDidLoad中完成我们对 NSFetchedResultsController 初始化。

//1
    let fetchRequest = NSFetchRequest(entityName: "Team")
    let sortDescriptor = NSSortDescriptor(key: "teamName",ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]
    //2
    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,managedobjectContext: coreDataStack.context,sectionNameKeyPath: nil,cacheName: nil)
        do {
        try fetchedResultsController.performFetch()
    } catch let error as NSError {
        print("Error: \(error.localizedDescription)")
    }
  1. fetchedResultsController 是数据和表格视图之间的协调,但它仍然需要你提供一个NSFetchRequest .但是你要记住, NSFetchRequest类是高度可制定的,它可以配置 sort descriptors,predicates 等等 因为在我们这个例子中要获取全部的对象,所以就不配置了。后两个参数先暂时为nil 吧,之后再讲解。但是的但是,我们必须要给 NSFetchRequest 配置 sortdescriptors,否则他不知道您的表格视图内容应该如何排序。我们这里按照teamName 升序排列

  2. 之后我们要执行获取请求。也许你会疑惑,我们获取的数据存储到了哪里呢?NSFetchedResultsController 不会返回任何东西。我们可以通过一个属性(fetchedobjects)和一个方法(objectAtIndexPath)来获取对象

接下里完成我们表格的数据源和单元格的配置

extension ViewController: UITableViewDataSource {
  
  func numberOfSectionsInTableView
    (tableView: UITableView) -> Int {
      
      return fetchedResultsController.sections!.count
  }
  
  func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
      
      return fetchedResultsController.sections![section].numberOfObjects
  }
  
  func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath)
    -> UITableViewCell {
      let team = fetchedResultsController.objectAtIndexPath(indexPath) as! Team
      let cell =
      tableView.dequeueReusableCellWithIdentifier(
        teamCellIdentifier,forIndexPath: indexPath)
        as! TeamCell
      
      cell.flagImageView.image = UIImage(named: team.imageName!)
      cell.teamLabel.text = team.teamName
      cell.scoreLabel.text = "Wins:\(team.wins)"
      
      return cell
  }
}
run your app , your are Success !!!

Modifying data

extension ViewController: UITableViewDelegate {
  
  func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
      
        let team = fetchedResultsController.objectAtIndexPath(indexPath) as! Team
        let wins = team.wins!.integerValue
        team.wins = NSNumber(integer: wins + 1)
        coreDataStack.saveContext()
        tableView.reloadData()
  }
}

用户点击某个单元格的时候,wins数目就会改变。

Grouping results into sections

接下来呢我们让 Team entity 通过它的属性qualifyingzone 来进行分组。 返回我们的viewDidLoad 来改变 controller's 的初始化。

fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,sectionNameKeyPath: "qualifyingzone",cacheName: nil)

Note: sectionNameKeyPath takes a keyPath string. It can take the form of an attribute name such as “qualifyingzone” or “teamName”,or it can drill deep into a Core Data relationship,such as “employee.address.street”.

改变每个Section的名字

func tableView(tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
       let sectionInfo = fetchedResultsController.sections![section]
       return sectionInfo.name
   }

接下来我们改变给每个 section 里的cell 的排序。在 viewDidLoad中改变 fetchRequest.sortDescriptors

let sortDescriptor = NSSortDescriptor(key: "teamName",ascending: true)
   let zonesort = NSSortDescriptor(key: "qualifyingzone",ascending: true)
   let scoreSort = NSSortDescriptor(key: "wins",ascending: false)
   fetchRequest.sortDescriptors = [zonesort,scoreSort,sortDescriptor]

添加了三个 sortDescriptors : zonesortscoreSortsortDescriptor
会按照先后顺讯来。比如说 两个 cell zonesort是相同的,那么就看他们的scoreSort ...

“Cache” the ball

开启缓存很简单。

fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,cacheName: "worldCup")

没错就是这么简单。

NSFetchedResultsController的部分缓存是在其读取请求的变化非常敏感。你可以想像,任何改变,如不同的实体描述或不同的排序描述,会给你一个完全不同的集获取的对象,完全无效的高速缓存。如果你做这样的更改,则必须删除使用deleteCacheWithName现有的缓存:或使用不同的缓存名称

Monitoring changes

`NSFetchedResultsController`可以侦听在其结果集中的变化,并通知其委托,`NSFetchedResultsControllerDelegate`。根据需要随时基础数据的变化可以使用该委托刷新表视图。
是什么意思,一个读取的结果控制器可以监控在其“结果集”的变化?这意味着它可以监视所有对象,新旧的变化,这要取,除了它已经取出的对象。这个区别会在本节后面变得更加清晰。

extension ViewController: NSFetchedResultsControllerDelegate {
    
}
//在viewDidLoad中

fetchedResultsController.delegate = self

已取得的成果控制器只能通过监控在其初始指定的托管对象上下文所做的更改。如果您创建一个单独的NSManagedobjectContext在你的应用在其他地方,并开始有变化,你的委托方法将无法运行,直到这些变化被保存并与读取的结果控制器的情况下合并。

Responding to changes

首先呢,我们将tableView(_:didSelectRowAtIndexPatch:)中的reloadData方法删除。我们来使用NSFetchedResultsControllerDelegate方法来在数据改变的时候刷新界面。

func controllerDidChangeContent(controller: NSFetchedResultsController) {
        tableView.reloadData()
    }

不要小看这小小的变化。现在你运行app,点击任意一个cell你回发现视图会立马改变,包括cell的位置也会发生改变。

func controllerWillChangeContent(controller: NSFetchedResultsController) {
        tableView.beginUpdates()
    }
    
    func controller(controller: NSFetchedResultsController,didChangeObject anObject: AnyObject,atIndexPath indexPath: NSIndexPath?,forChangeType type: NSFetchedResultsChangeType,newIndexPath: NSIndexPath?) {
        
        switch type {
        case .Delete :
            tableView.deleteRowsAtIndexPaths([newIndexPath!],withRowAnimation: .Automatic)
        case .Insert :
            tableView.insertRowsAtIndexPaths([indexPath!],withRowAnimation: .Automatic)
        case .Update :
            let cell = tableView.cellForRowAtIndexPath(indexPath!) as! TeamCell
            configureCell(cell,indexPath: indexPath!)
        case .Move :
            tableView.deleteRowsAtIndexPaths([indexPath!],withRowAnimation: .Automatic)
            tableView.insertRowsAtIndexPaths([newIndexPath!],withRowAnimation: .Automatic)
        }
    }
    
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
        tableView.endUpdates()
    }
func controller(controller: NSFetchedResultsController,didChangeSection sectionInfo: NSFetchedResultsSectionInfo,atIndex sectionIndex: Int,forChangeType type: NSFetchedResultsChangeType) {
        let indexSet = NSIndexSet(index: sectionIndex)
        switch type {
        case .Insert:
            tableView.insertSections(indexSet,withRowAnimation: .Automatic)
        case .Delete:
            tableView.deleteSections(indexSet,withRowAnimation: .Automatic)
        default:
            break
        }
    }

Inserting an underdog

override func motionEnded(motion: UIEventSubtype,withEvent event: UIEvent?) {
        if motion == .MotionShake {
            addButton.enabled = true
        }
    }
    
    @IBAction func addTeam(sender: AnyObject) {
        let alert = UIAlertController(title: "Secret",message: "Add a new team",preferredStyle: .Alert)
        alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
            textfield.placeholder = "Team Name"
        }
        alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
            textfield.placeholder = "Qualifying Zone"
        }
        
        alert.addAction(UIAlertAction(title: "Save",style: .Default,handler: { (actino) -> Void in
            let nametextfield = alert.textFields!.first
            let zoneTextField = alert.textFields![1]
            
            let team = NSEntityDescription.insertNewObjectForEntityForName("Team",inManagedobjectContext: self.coreDataStack.context) as! Team
            team.teamName = nametextfield!.text
            team.qualifyingzone = zoneTextField.text
            team.imageName = "wenderland-flag"
            self.coreDataStack.saveContext()
        }))
        
        alert.addAction(UIAlertAction(title: "Cancel",handler: { (action) -> Void in
            print("Cancel")
        }))
        presentViewController(alert,animated: true,completion: nil)
    }

Where to go from here?

最终项目

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...