【发布时间】:2012-08-27 05:13:30
【问题描述】:
我已经实现了一个使用 UITableViewController/UITableView 和 Core Data 的 iPhone 应用程序。此外,我使用 NSFetchedResultsController 来管理表数据。这一切都非常简单,而且效果很好。然后我决定当没有找到/检索到行时,我应该在 UITableView 中显示一条消息。在对此进行研究之后,似乎最好的方法(也许是唯一的方法)是返回一个包含消息的“虚拟”单元格。但是,当我这样做时,我从运行时系统中得到一个讨厌的图,它抱怨(并且理所当然地)数据不一致:“无效更新:无效的节数。表视图中包含的节数......”。以下是相关代码:
- (NSInteger) numberOfSectionsInTableView: (UITableView *)tableView
{
if ([[self.fetchedResultsController fetchedObjects] count] == 0) return 1;
return [[self.fetchedResultsController sections] count];
}
- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[self.fetchedResultsController fetchedObjects] count] == 0) return 1;
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex: section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *) tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
if ([[self.fetchedResultsController fetchedObjects] count] == 0) {
UITableViewCell *cell = [[UITableViewCell alloc] init];
cell.textLabel.text = @"No widgets found.";
return cell;
}
STCellView *cell = (STCellView *)[tableView dequeueReusableCellWithIdentifier: @"ShieldCell"];
[self configureCell: cell atIndexPath: indexPath];
return cell;
}
我已阅读类似问题的回复,看来我应该使用
insertRowsAtIndexPaths: withRowAnimation:
将“虚拟”消息行插入我的表中。但是,这也意味着在插入真实行时删除“虚拟”行。我可以做到这一点,但似乎应该有一种更简单的方法来实现这一点。我要做的就是显示一条消息,指示表中没有行(够简单吗?)。所以,我的问题是:有没有办法在 UITableView 中显示一条消息而不使用“虚拟”单元格方法,或者有没有办法让 UITableViewController/NSFetchResulsController 相信这只是一个“虚拟”行,他们不应该得到因为它不是表格中的真实行(从我的角度来看),所以对此感到不安?
您能提供的任何帮助都将不胜感激(我是 iPhone 开发的一个苦苦挣扎的新手,我想学习最佳实践)。谢谢。
【问题讨论】:
-
与其破解 tableview 数据源以获得预期的 UI,为什么不将“No rows found”消息添加到 tableview 标头?
-
如果您的表格视图中只有一个部分,这是最好的方法。请参阅下面的多个部分的方法
-
@Rog 这是完美的答案。在 viewWillAppear 中,如果行数为 0,我会加载一个表格视图标题。不幸的是,因为您没有输入这个作为答案,我无法选择它,但它(在我看来)是最干净和最好的答案。非常感谢。
-
谢谢,很高兴它对你有用。我已将其添加为答案,以便其他人将来可以轻松找到它,因此下次您在附近时随时将其标记为正确。
标签: iphone core-data uitableview nsfetchedresultscontroller