How to reloadData in class which implements UITableViewDataSource protocol
I have a class which implements UITableViewDelegate protocol and there is another class which handles data i.e. it implements UITableViewDataSource protocol.
@interface TableViewClass : UITableViewController <UITableViewDelegate>
@interface TableDataSource : NSObject <UITableViewDataSource>
and I'm setting the TableViewClass as delegate and TableDataSource as data开发者_如何学Csource
id datasource = [[TableDataSource alloc] init]
[self.tableView setDelegate:self];
[self.tableView setDataSource:dataSource];
I am fetching the data off an asynchronous server call in init method of TableDataSource class which populates an array and determines the number of rows/sections in table.
But before the call returns back some result, the numberOfSectionsInTableView
and numberOfRowsInSection
are executed resulting in 0 rows and 0 sections, hence an empty table.
I thought of putting the [self.tableView reloadData]
in callBack but I do not have access to tableView in datasource class.
Can anybody guide me how to reloadData in tableView through datasource class as I might need it later to refresh data too.
Thanks
To solve this quickly, you can add an @property on TableDataSource for the 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 you create 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 the data from the DataSource, you can now do:
[self.tableView reloadData];
精彩评论