sectionNameKeyPath与NSFetchedResultsController无法正常工作

时间:2011-07-06 23:12:45

标签: iphone objective-c cocoa-touch core-data nsfetchedresultscontroller

我有一个实体Order,其属性为paid,这是一个布尔值。

我想在UITableView中显示所有订单,但我想将它们分为两部分:'未付款'和'付费'。所以我认为我只是给“付费”sectionNameKeyPath,就像这样:

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

根据我的推理,这将产生两个部分,其中第一部分包含所有带有付款= NO(0)的订单,第二部分包含付款= YES(1)。

但是当我添加一个带有paid = YES的新订单时,它会显示在第一部分中。当我签入获取结果控制器委托时,我可以看到创建了一个带有indexPath [0,0]的新记录!为什么不插入第二部分?

1 个答案:

答案 0 :(得分:15)

尝试将一个排序描述符数组添加到与NSFetchedResultsController一起使用的NSFetchRequest中。

您首先需要对付费布尔值进行排序,然后根据您要排序的其他内容进行排序。

Swift 3示例:

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