UITableView delegate method called twice

≡放荡痞女 提交于 2019-11-26 16:35:51

问题


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.


回答1:


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




回答2:


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]




回答3:


Please check your code, after adding TableView you may again called realodData method of table in mey be ViewWillAppear method




回答4:


This can happen if you'r table view's frame gets changed by mistake in the story board.Say you clicked on the storyboard where you have added the table view as a subview and now your table may not be having the proper frame which you have set in the beginning.



来源:https://stackoverflow.com/questions/2638359/uitableview-delegate-method-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!