Search code examples
uitableviewcore-datansfetchedresultscontrollerswift5

Different sections in tableView from NSFetchedResultsController than in Core Data records


I have 2 entities: Products and Package Products have name,weight,price and relationship to Package pack->To Many Package have name and I use it for the sections in my tableView.

Products are created with textFields and tableView is populated with [Package]. In the Core Data I record pack to be selectedRow Package , but when I open the tableView with Products the products are in different packages(sections) than I selected in tableView of Package

Results from Core Data:

"prod4"
<Packings: 0x2817a5770> (entity: Packings; id: 0xbf7e2ae6e8ae5fb1 <x-coredata://9D72FE26-796C-42CF-A3E0-1E1A3B7071AF/Packings/p1>; data: <fault>)

"prod3"
<Packings: 0x2817b2cb0> (entity: Packings; id: 0xbf7e2ae6e8a65fb1 <x-coredata://9D72FE26-796C-42CF-A3E0-1E1A3B7071AF/Packings/p3>; data: <fault>

"prod2"
<Packings: 0x2817b2d50> (entity: Packings; id: 0xbf7e2ae6e8a25fb1 <x-coredata://9D72FE26-796C-42CF-A3E0-1E1A3B7071AF/Packings/p2>; data: <fault>)

"prod1"
<Packings: 0x2817a5770> (entity: Packings; id: 0xbf7e2ae6e8ae5fb1 <x-coredata://9D72FE26-796C-42CF-A3E0-1E1A3B7071AF/Packings/p1>; data: <fault>)

As you can see prod1, prod2, prod3 should be refereed to pack1, pack2, pack3 described in the print as p1,p2,p3. prod4 is refereed to p1. But they are arranged completely different in the Products tableView:

Results Code:

let fetchRequest:NSFetchRequest<Products> = Products.fetchRequest()
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "productId", ascending: false)]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: (UIApplication.shared.delegate as? AppDelegate)!.persistentContainer.viewContext, sectionNameKeyPath: "pack.name", cacheName: nil) as? NSFetchedResultsController<NSFetchRequestResult>
fetchedResultsController!.delegate = self
try fetchedResultsController!.performFetch()



func numberOfSections(in tableView: UITableView) -> Int {
    return fetchedResultsController?.sections?.count ?? 0
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return fetchedResultsController?.sections![section].name
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return fetchedResultsController!.sections![section].numberOfObjects
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let product = fetchedResultsController!.object(at: indexPath) as! Products
}

Solution

  • To sort the sections properly you have to specify an appropriate sort descriptor at first position.

    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "pack.name", ascending: false),
                                    NSSortDescriptor(key: "productId", ascending: false)]