sectionNameKeyPath with NSFetchedResultsController not working

左心房为你撑大大i 提交于 2019-12-12 10:36:56

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/6604115/sectionnamekeypath-with-nsfetchedresultscontroller-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!