Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView delegate method called twice

Today my question is about UITableViewController-s In particular I have noticed that the datasource delegate method

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

is called twice (even if for instance I just create a navigation based application and without adding a line of code.. well adding an NSLog to track it). Now, since in my application I need to determine the number of sections basing the choice on the documents in the file system, I need to call some methods to do so. I have put these methods in the above mentioned method, so they will be called twice, which is something I don't need. The questions are why is it called twice, can I have it called once? I hope that in the official documentation this is not clearly stated (which would mean that I didn't read it at all :) ). By the way I could see others posting similar questions, but I couldn't find a fully satisfying answer. Thank you.

like image 747
user236739 Avatar asked Apr 14 '10 14:04

user236739


2 Answers

I was experiencing the same problem, only with the call to numberOfRowsInSection: The answered laid in the stack trace for each call I received.

  1. The first call was due to a change in the table header view I was making in the viewDidLoad: of my viewcontroller.

    thumbView.tableHeaderView = nil;
    thumbView.tableFooterView = nil;
    

    This resulted in internal call to _updateContentSize: which called heightForTable: which eventually called numberOfRowsInSection:. This was something I triggered, and could be easily avoided by not doing the above code :)

  2. The second call was the legitimate one in order to reloadData. This is triggered by a layout event somewhere and most likely you can't skip it.

I'm sure you can observe something similar for the numberOfSections: method

So, my conclusion is that due to the the implementation of UITableView there are many situations where certain delegate methods will get called twice or more because the table view has to refresh something. I try to design my code around this bug/feature/etc.

Hope it helps

like image 62
Andrei Stanescu Avatar answered Nov 15 '22 23:11

Andrei Stanescu


If your tableview is contained by a child view controller, Try this at your parent ViewController

[parentViewController addChildViewController:childViewController];

before [parentViewController.view addSubview:childViewController.view]

like image 31
Wanbok Choi Avatar answered Nov 15 '22 22:11

Wanbok Choi