上篇文章寫了數(shù)據(jù)的操作豹爹,今天簡單的介紹NSFetchedResultsController的使用,文中不足之處還請各位小伙伴加以指正党巾。
NSFetchedResultsController和TableView搭配會(huì)非常的好用萎庭,假設(shè)CoreData中的實(shí)體為Team,Team包含qualifyingZone齿拂、wins驳规、teamName三個(gè)屬性。
var fetchResultController : NSFetchedResultsController!
let fetchRequest = NSFetchRequest(entityName: "Team")
//可以通過以下方式進(jìn)行信息排序署海,最終排序結(jié)果依賴 fetchRequest.sortDescriptors 數(shù)組中的數(shù)據(jù)順序
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路徑下有多少個(gè)值,tableview就會(huì)被劃分多少個(gè)部分.如果不想分區(qū)可以將sectionNameKeyPath置為nil
cacheName:存放緩存數(shù)據(jù)的地方砸狞,避免每刷新一次都要從新請求捻勉,適用于數(shù)據(jù)較多的時(shí)候,獨(dú)立于數(shù)據(jù)持久化存儲(chǔ)刀森。比如NSFetchedResultsController第一次從持久化存儲(chǔ)中讀取數(shù)據(jù)踱启,如果有cacheName,第二次的數(shù)據(jù)會(huì)從緩存中讀研底,比第一次會(huì)快一點(diǎn)
*/
TableView數(shù)據(jù)源
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
}