美文网首页iOS开发程序员
CoreData之NSFetchedResultsControl

CoreData之NSFetchedResultsControl

作者: 章鱼卷 | 来源:发表于2016-05-19 20:47 被阅读0次

    上篇文章写了数据的操作,今天简单的介绍NSFetchedResultsController的使用,文中不足之处还请各位小伙伴加以指正。

    NSFetchedResultsController和TableView搭配会非常的好用,假设CoreData中的实体为Team,Team包含qualifyingZone、wins、teamName三个属性。

    var fetchResultController : NSFetchedResultsController!
    let fetchRequest = NSFetchRequest(entityName: "Team")
    

    //可以通过以下方式进行信息排序,最终排序结果依赖 fetchRequest.sortDescriptors 数组中的数据顺序

    let zoneSort = NSSortDescriptor(key: "qualifyingZone", ascending: true)
    let scoreSort = NSSortDescriptor(key: "wins", ascending: false)
    let nameSort = NSSortDescriptor(key: "teamName", ascending: true) 
    fetchRequest.sortDescriptors = [zoneSort,scoreSort,nameSort]
    
     fetchResultController=NSFetchedResultsController(fetchRequest:fetchRequest,managedObjectContext:cdh.managedObjectContext,sectionNameKeyPath:"qualifyingZone", cacheName: "WordCup")
      fetchResultController.delegate = self 
        do{
            try fetchResultController.performFetch()
        }catch let error as NSError {
            print(error)
        }
    

    /*
    sectionNameKeyPath的值用来划分tableview的session,sectionNameKeyPath路径下有多少个值,tableview就会被划分多少个部分.如果不想分区可以将sectionNameKeyPath置为nil

    cacheName:存放缓存数据的地方,避免每刷新一次都要从新请求,适用于数据较多的时候,独立于数据持久化存储。比如NSFetchedResultsController第一次从持久化存储中读取数据,如果有cacheName,第二次的数据会从缓存中读,比第一次会快一点
    */

    TableView数据源

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
        return fetchResultController.sections!.count
    }
    
    override fun     tableView(tableView:UITableView,titleForHeaderInSection section:Int) -> String? {
        let sectionInfo = fetchResultController.sections![section]
        return sectionInfo.name
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionInfo = fetchResultController.sections![section]
        return sectionInfo.numberOfObjects
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier") 
        let team = fetchResultController.objectAtIndexPath(indexPath) as! Team
        cell.textLabel.text = team.teamName
        return cell
    }

    相关文章

      网友评论

        本文标题:CoreData之NSFetchedResultsControl

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