上篇文章寫了數(shù)據(jù)的操作,今天簡單的介紹NSFetchedResultsController的使用,文中不足之處還請各位小伙伴加以指正。
NSFetchedResultsController和TableView搭配會非常的好用,假設CoreData中的實體為Team,Team包含qualifyingZone、wins、teamName三個屬性。
var fetchResultController : NSFetchedResultsController!
let fetchRequest = NSFetchRequest(entityName: "Team")
//可以通過以下方式進行信息排序,最終排序結(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路徑下有多少個值,tableview就會被劃分多少個部分.如果不想分區(qū)可以將sectionNameKeyPath置為nil
cacheName:存放緩存數(shù)據(jù)的地方,避免每刷新一次都要從新請求,適用于數(shù)據(jù)較多的時候,獨立于數(shù)據(jù)持久化存儲。比如NSFetchedResultsController第一次從持久化存儲中讀取數(shù)據(jù),如果有cacheName,第二次的數(shù)據(jù)會從緩存中讀,比第一次會快一點
*/
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
}