简体   繁体   中英

When is tableView:numberOfRowsInSection: called in UITableView?

tableView:numberOfRowsInSection is sent to the delegate of a UITableView to find out how many rows it needs to have in a given section.

My question is, when and how often is this method called?

在第一次加载tableview时调用该方法,如果您对委托更感兴趣,则放置一个断点并检查调用哪个委托的时间和位置以及多少次。

Below are the instances when that function will get called,

  1. For the first time when table is loaded
  2. the time you reload the table data
  3. the time you add/update/delete your row or sections dynamically.

The method - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section is a protocol method of the UITableViewDataSource - protocol . It will be called the very first time your table view is loaded based on that you have set the dataSource properly, eg

self.yourTableView.dataSource = self;

If you are interested in updating your table again at a later time you can call

[self.yourTableView reloadData];

in order to reload the entire table. If you are only interested in reloading a part of your table you can do something similar to

NSIndexSet *reloadSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [self numberOfSectionsInTableView:self.yourTableView])];
[self.yourTableView reloadSections:reloadSet withRowAnimation:UITableViewRowAnimationAutomatic];

Hope it helps!

My question is, when and how often is this method called?

Short Answer : When your UITableView needs to update something.

Long Answer : Delegates Methods generally called themselves however it may be called multiple times when your UITableView needs to update something. By default, it's called very first time the tableview is getting loaded or updated (reloaded).

It depends on how often user will scroll UITable view to section and how many sections there are. This value, which is returned by this function and is casched. Method will need be revoked if you will update content of table view (filtering results, or updating data via reloadData ).

Best thing for you will be to add logging to this function and check this yourself.

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