Sectioning TableView and rows with Core Data Swift

◇◆丶佛笑我妖孽 提交于 2019-12-03 08:52:22

Just a hint: If you're using CoreData and UiTableView use NSFetchedResultsController to make things much, much easier. If you're searching for a starting point & sample code - just create a new master-detail-application project in Xcode and turn on "Use Core Data" in the dialog.

Now, straight to your question: an example "implementation" of the NSFetchResultsController:

var fetchedResultsController: NSFetchedResultsController {

  if _fetchedResultsController != nil {
       return _fetchedResultsController!
   }
   let fetchRequest = NSFetchRequest()
   // Edit the entity name as appropriate.
   let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
   fetchRequest.entity = entity

   // Set the batch size to a suitable number.
   fetchRequest.fetchBatchSize = 20

   // Edit the sort key as appropriate.
   let sectionSortDescriptor = NSSortDescriptor(key: "startDate", ascending: true)
   let secondSortDescriptor = NSSortDescriptor(key: "title", ascending: true)

   let sortDescriptors = [sectionSortDescriptor, secondSortDescriptor]

   fetchRequest.sortDescriptors = sortDescriptors

   // Edit the section name key path and cache name if appropriate.
   // nil for section name key path means "no sections".
   let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: "startDate", cacheName: nil)
   aFetchedResultsController.delegate = self
   _fetchedResultsController = aFetchedResultsController

   var error: NSError? = nil
   if !_fetchedResultsController!.performFetch(&error) {
       // Replace this implementation with code to handle the error appropriately.
       // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
       //println("Unresolved error \(error), \(error.userInfo)")
       abort()
   }

   return _fetchedResultsController!
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return self.fetchedResultsController.sections?.count ?? 0
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let sectionInfo = self.fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
    return sectionInfo.numberOfObjects
}
Weles

According to crosscode's answer!

I did some changes!

1 - I needed to implement NSFetchedResultsControllerDelegate protocol;

2 - I needed to declare the fechedResultsController

3 - I needed to set the correct table in entity for NSEntityDescription;

4 - I needed to navigate in relationship to group by startdate in sectionNameKeyPath

Now the code:

//1 - implementing protocol
class AgendaViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {

    //2 - declare the fechedResultsController
    var fetchedResultsController: NSFetchedResultsController = NSFetchedResultsController()

    override func viewDidLoad() {
        super.viewDidLoad()

        getFetchedResultController()       
    }

    func getFetchedResultController() {

        let appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let moc: NSManagedObjectContext = appDel.managedObjectContext!

        let fetchRequest = NSFetchRequest()

        //3 - set the correct table
        let entity = NSEntityDescription.entityForName("EventDetail", inManagedObjectContext: moc)
        fetchRequest.entity = entity

        fetchRequest.fetchBatchSize = 20

        let sectionSortDescriptor = NSSortDescriptor(key: "event.startDate", ascending: true)

        let sortDescriptors = [sectionSortDescriptor] //, secondSortDescriptor]

        fetchRequest.sortDescriptors = sortDescriptors

        //4 - navigate in relationship to group by startdate 
        let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: "event.startDate", cacheName: nil)

        aFetchedResultsController.delegate = self
        self.fetchedResultsController = aFetchedResultsController

        var error: NSError? = nil
        if !self.fetchedResultsController.performFetch(&error) {
            abort()
        }
    }

    func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
        return self.fetchedResultsController.sections?.count ?? 0
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionInfo = self.fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
        return sectionInfo.numberOfObjects
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!