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.

6
  • 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. Commented Sep 4, 2018 at 2:09
  • What exception? Try to handle it after you've created the datasource. Commented Sep 4, 2018 at 2:32
  • @rmaddy, something like checking [fetchedResultsController.fetchedObjects count] in viewdidload? Commented Sep 4, 2018 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. Commented Sep 4, 2018 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; Commented Sep 4, 2018 at 16:40

1 Answer 1

-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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.