I am trying to display a message of no results found when a fetched results controller returns no rows as here.
To do this, I am putting code in the numberOfRows method. However, it is throwing an exception. Here is my code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];
int numRows =[sectionInfo numberOfObjects];
if (numRows>=1) {
return [sectionInfo numberOfObjects];
}
else {
UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
messageLabel.text = @"No comments yet.";
messageLabel.textColor = [UIColor grayColor];
messageLabel.numberOfLines = 0;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
return 0;
}
}
Should I be putting this code elsewhere? Or what could be wrong with it that would cause it to throw an exception.
Thanks in advance for any suggestions.
numberOfRowsInSection(and other data source methods) can be called many, many times. You should not be loading data in that method. You should not be creating and adding views from that method.