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?
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
精彩评论