Search code examples
iosswiftuitableviewsortingnsfetchedresultscontroller

multiple sections with different order using 1 NSFetchedResultsController


I have a tableview with two sections, "favorite" and "recent" to order stored contacts. I would like to sort the favorite alphabetically, and the recent by date. Each contact has a "name" and a "createdAt" value (and a value "favorite" if it is a favorite).

Using the sort below I have my sections "favorite" and "recent" with the correct cells but both sorted alphabetically.

...
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "favorite", ascending: false),
                                    NSSortDescriptor(key: "firstName", ascending: true)]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: stack.viewContext, sectionNameKeyPath: "favorite", cacheName: nil)
...

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    guard let currentSection = fetchedResultsController.sections?[section] else { return nil }

    if currentSection.name == "0" {
        return "Recent".localized
    } else {
        return "Favorites".localized
    }
}

How can I sort the section "recent" by date?


Solution

  • I solved it by manually changing the indexPath of the second section. I have a function that return indexPath ordered differently for the second section.

    func changeIndexPath (_ indexPath: IndexPath) -> IndexPath {
    ... //sort you want
    }
    

    Then I can use the functions of the tableview

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    ...
    newIndexPath = changeIndexPath(indexPath)
    ...
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    ...
    }
    etc