简体   繁体   中英

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.

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

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]

请检查你的代码,添加后TableView你现在又可以称为realodData在MEY表的方法ViewWillAppear的方法

如果您的表格视图的框架在故事板中被错误更改,则会发生这种情况。您点击故事板上已将表格视图添加为子视图,现在您的表格可能没有您设置的正确框架在一开始的时候。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM