Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sectionNameKeyPath with NSFetchedResultsController not working

I have an entity Order with property paid, which is a boolean.

I want to display all orders in a UITableView, but I want to group them in two sections: 'Not Paid' and 'Paid'. So I thought I'd just give "paid" as sectionNameKeyPath, like this:

fetchedResultsController = [[NSFetchedResultsController alloc]
         initWithFetchRequest:fetchRequest
         managedObjectContext:managedObjectContext
           sectionNameKeyPath:@"paid"
                    cacheName:nil];

According to my reasoning, this would result in two sections, where the first section contains all orders with paid = NO (0) and the second section with paid = YES (1).

But when I add a new Order with paid = YES, it shows up in the first section. When I check in the fetched results controller delegate, I can see that a new record with indexPath [0,0] is created! Why doesn't it get inserted in the second section?

like image 521
Rits Avatar asked Jul 06 '11 23:07

Rits


1 Answers

try adding an array of sort descriptors to the NSFetchRequest that is used with your NSFetchedResultsController.

You will want to sort on the paid boolean first, then whatever else you want to sort by.

Swift 3 example:

fetchRequest = ... // <- instantiate your fetch request

let sortByPaid = NSSortDescriptor(key: "paid", ascending: true)
let sortByCustomerName = NSSortDescriptor(key: "customer.name", ascending: true) // <- if Order had a relationship to Customer that had an attribute name 
fetchRequest.sortDescriptors = [sortByPaid, sortByCustomerName]

// now instantiate fetchedResultsController as in the question above
like image 85
timthetoolman Avatar answered Sep 19 '22 18:09

timthetoolman