2012-05-31 55 views
2

我正在使用主/細節機制。 tableview控制器利用[controller:(NSFetchedResultsController *)控制器didChangeObject:...]刷新相關行。 它適用於插入和刪除。如何使用CoreData和NSFetchedResultsController在UITableView中實現邏輯刪除

現在我想不真的刪除行,只是「隱藏」它們。

因此,我在我的核心數據模型中添加了一個布爾型「已刪除」,而我的主人使用一個謂詞來僅提取「deleted = FALSE」。

在[控制器:(NSFetchedResultsController *)控制器didChangeObject:...]我需要:

  • 支票NSFetchedResultsChangeUpdate。
  • 如果是這樣,我可能需要'刷新'le fetchedResultController(不知道它是否可以檢測到與謂詞匹配的managedObject不再匹配),我需要從tableview中刪除該行。

下面是代碼:

case NSFetchedResultsChangeUpdate: 
    // This is fired by saving managedObject.deleted from FALSE to TRUE 
    // ... so I would like to delete the corresponding row from the tableview 
    // without reloading the full table. 
    self.fetchedResultsController = nil; 
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
break; 

但預期它不工作,並與錯誤信息中庸之道崩潰:

2012-05-31 09:48:23.293 TableViewTest[32701:fb03] CoreData: error: 
``Serious application error. 
An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. 
Invalid update: invalid number of rows in section 0. 
The number of rows contained in an existing section after the update (7) 
must be equal to the number of rows contained in that section before the update (7), 
plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) 
and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). 
with userInfo (null) 

的信息是明確的,NSFetchedResultsController不要」 t返回正確的計數。通過啓用CoreData請求日誌,似乎在此方法中,更改尚未提交。

我嘗試了不同的方法:

  • 確保NSFetchedResults真正使請求(顯式調用讀取,刪除緩存)。
  • 我試圖指定[fetchRequest includesPendingChanges]包括尚未COMMITED變化

但我一直有同樣的問題。 它爲什麼適用於插入和真正的刪除(插入和刪除不提交,但被NSFetchedResultsController看到)。 PS:爲了說明這個問題,我從Xcode模板創建一個新項目(使用CoreData + MasterController選項)。你可以在github上找到它https://github.com/arnauddelattre/TableViewTest。您可以嘗試添加一些行,然後選擇一行並單擊「邏輯刪除」。

_

編輯:按照與曼迪響應 芒迪建議我打電話保存方法在管理範圍內。 正如你所看到的,我已經在save方法中調用了[controller didChangeObject]。 因此,它導致在保存中調用保存。 Stack in XCode screenshot

對我來說奇怪的是,它似乎在工作。但是我害怕可能的副作用(因爲保存中調用保存)。這是實現我想要的「標準」方式嗎?

而我仍然不明白爲什麼這種行爲不同於插入/真正的刪除。

回答

1

在將fetchedResultsController設置爲nil之前,您可以保存(提交)NSFetchedResultsChangeUpdate回調中的更改。

+0

我按照您的建議修改了我的問題 –

+0

保存是與數據相關的活動。更改抓取的結果控制器是依賴於數據的UI相關活動。因此,如果這些更改沒有被提交以通知他提取的結果控制器,那麼在回調中執行它是有意義的。我認爲你不必擔心儲蓄「兩次」。 – Mundi