How to reload Data in a class that implements the UITableViewDataSource protocol

I have a class that implements the UITableViewDelegate protocol, and there is another class that processes data, that is, implements the UITableViewDataSource protocol.

@interface TableViewClass : UITableViewController <UITableViewDelegate> @interface TableDataSource : NSObject <UITableViewDataSource> 

and I set TableViewClass as a delegate and TableDataSource as a data source

 id datasource = [[TableDataSource alloc] init] [self.tableView setDelegate:self]; [self.tableView setDataSource:dataSource]; 

I retrieve data from an asynchronous server call in the init method from the TableDataSource class, which fills the array and determines the number of rows / sections in the table.

But before the call returns some result, numberOfSectionsInTableView and numberOfRowsInSection will be executed, the result will be 0 rows and 0 sections, and therefore an empty table.

I was thinking about putting [self.tableView reloadData] in a callBack, but I don't have access to the tableView in the datasource class. Can someone tell me how to reload Data in a tableView through the datasource class, as I may need this later to update the data. Thanks

+4
source share
1 answer

To quickly solve this problem, you can add @property to TableDataSource for UITableView.

 // TableDataSource.h @interface TableDataSource : NSObject <UITableViewDataSource>{ UITableView *tableView; } @property(retain)UITableView *tableView; @end // TableDataSource.m @implementation TableDataSource @synthesize tableView; - (void)dealloc{ self.tableView = nil; } @end 

Now set the property when creating the DataSource:

 // UITableViewController.m TableDataSource* datasource = [[TableDataSource alloc] init] [datasource setTableView:self.tableView] [self.tableView setDelegate:self]; [self.tableView setDataSource:dataSource]; 

When you need to reload data from a DataSource, you can do the following:

 [self.tableView reloadData]; 
+4
source

Source: https://habr.com/ru/post/1340704/


All Articles