8

我有一個實體Order與屬性paid,這是一個布爾值。sectionNameKeyPath NSFetchedResultsController不工作

我想在UITableView中顯示所有訂單,但我想將它們分爲兩部分:'未付'和'已付'。所以,我想我只是給「有償」爲sectionNameKeyPath,就像這樣:

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

根據我的推理,這將導致兩個部分,其中第一部分包含有付費= NO所有訂單(0)第二部分付費=是(1)。

但是,當我添加付款=是的新訂單時,它顯示在第一部分。當我檢查獲取的結果控制器委託時,我可以看到創建了一個帶有indexPath [0,0]的新記錄!爲什麼它沒有插入到第二部分?

回答

12

嘗試向您的NSFetchedResultsController中使用的NSFetchRequest添加一個排序描述符數組。

您需要首先對付費布爾值進行排序,然後選擇您想要排序的任何其他值。

斯威夫特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 
+0

你是老闆! – raed

+0

此外,添加的排序描述符(如果它是單個的)應該與用於生成密鑰路徑的描述符不同 – jackal

+0

那麼實際上該問題的答案是什麼?我該怎麼做? –

相關問題