0

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.

user6631314
  • 1,751
  • 1
  • 13
  • 44
  • 2
    `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. – rmaddy Sep 04 '18 at 02:09
  • What exception? Try to handle it after you've created the datasource. – Kerberos Sep 04 '18 at 02:32
  • @rmaddy, something like checking [fetchedResultsController.fetchedObjects count] in viewdidload? – user6631314 Sep 04 '18 at 13:48
  • 2
    @user6631314 Make sure that the label is always in the background view of the UITableView. Set it hidden or not as soon as you know how many results there are. That is probably somewhere else than in this method. – fishinear Sep 04 '18 at 16:38
  • Ok. I moved everything except toggle hidden to viewdidload. Now I just need to show hidden=NO for label once I have results of fetch. Can you suggest a method, other than delegate, that fires after the table has loaded (have the results of nsfetchedresultscontroller)? When I put code in viewwillappear, it still shows results==0; – user6631314 Sep 04 '18 at 16:40
  • Update. By moving the check of fetched objects to viewdidappear, I seem to get the needed count to Unhide the message without putting the code into the data source delegate methods. – user6631314 Sep 04 '18 at 17:04

1 Answers1

-1

Use number of sections methos instead of number of rows in section. Something like this.

if self.yourArray.count > 0 {
    return 1
} else {
   //Your Empty Message
   return 0
}
Im Batman
  • 1,842
  • 1
  • 31
  • 48