网上的 iOS 案例教程中,UITable 都是用 ViewController 作为数据源和代理,比如:
self.listTableView.dataSource = self;
self.listTableView.delegate = self;
但是这样做 ViewController 会变得很长,如何新建一个文件来存储数据源和代理方法?
天蓬老师2017-04-18 09:07:45
This is actually a question of how to split a very large source code.
Here are several methods recommended to you, all of which are better.
1. Independent datasource, delegate management class
@interface MyTableManager : NSObject <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
- (void)setupWithTableView:(UITableView *)tableView
@end
@interface MyTableManager ()
@property (nonatomic, strong) NSMutableArray *array;
@end
@implement MyTableManager
- (void)setupWithTableView:(UITableView *)tableView
{
if (_tableView != tableView) {
_tableView = tableView;
_tableView.delegate = self;
_tableView.dataSource = self;
// ...
// _array = ?
}
}
#param mark - DataSource
// ...
#param mark - Delegate
// ...
@end
Then you just need to initialize the manager at the appropriate place in the viewController, and then load the tableView.
The advantage of this method is that if you use the same management logic in many places, the code can be split very well.
If you just want to reduce the number of rows of viewController, and this management class is not suitable for each viewController, then there is another method, which is also good.
2. Use category to split files
// MyViewController.h
@interface MyViewController (TableView) <UITableViewDelegate, UITableViewDataSource>
@end
// MyViewController+TableView.m
@implement MyViewController (TableView)
// ...
@end
There is no one-size-fits-all solution, just find one that suits you.
巴扎黑2017-04-18 09:07:45
Both = your new class, just implement the protocol method in the new class