我有一個由NSFectchedResultsController支持的tableview,當我沒有FRC的結果時試圖顯示一個自定義單元格。我遇到的問題是BeginUpdates召回numberOfRowsInSection。我想保持tableview的活躍(而不是隻顯示一個圖像的位置),以便用戶可以執行拉動刷新。在numberOfRowsInSection中調用TableView BeginUpdates
的代碼:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self.fetchedResultsController.fetchedObjects count] == 0) {
if (!specialCellShowing) {
specialCellShowing = TRUE;
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
}
return 1;
}
else {
if (specialCellShowing) {
specialCellShowing = FALSE;
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
}
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
return [self.fetchedResultsController.fetchedObjects count];
}
}
問題是返回1;聲明。會發生什麼是第一次調用numberOfRowsInSection它設置specialCellShowing = TRUE並命中開始更新,這會調用numberOfRowsInSection。方法的begin更新實例看到specialCellShowing爲true並返回1並退出。現在進行插入調用,然後崩潰發生在endUpdates上,因爲tableview認爲表中有1個單元,插入了1個單元,之前有1個單元。另一個問題是我需要返回1,因爲在隨後的numberOfRowsInSection調用中,我希望它不會與表格混淆,只是返回說我有一個自定義單元格。
我想我想知道的是,如果有更好的方法來處理這個問題?
你實際上可以改變它。我有一些非常笨拙的代碼,在一些情況下這樣做,插入和刪除工作在某些情況下。我應該這樣做嗎?可能不會。我會研究你的建議。我認爲我只是需要擺脫思考的想法 – TheJer
不要直接添加或刪除'numberRowsInSection'中的單元格。充其量,你正在玩火。 在numberOfRowsInSection期間可以隨意修改模型,但當您直接獲取cellForRowAtIndexPath:方法時,您返回的數字將用作最大索引。 MVC規定你應該改變模型以響應一個事件,然後告訴視圖它需要更新。在視圖更新期間,您不應該改變模型。 –
完全理解。你能不能指出我的方向來了解更多關於視圖更新週期的知識(就像哪種方法按照哪個順序調用?)。基本上,這聽起來像我需要聽更新完成,根據需要修改表,這將創建我自己的更新。那我應該很好? – TheJer