在使用MVC架構(gòu)模式書寫代碼的過程中,難免會遇到大量的代理方法寫在控制器(C)里面,使得控制器代碼異常龐大并且不便于閱讀。
這種情況下可以選擇將一部分代理方法代碼抽到代理類里面,從而達到一定程度的優(yōu)化。
如下是實現(xiàn)步驟代碼:
- 實現(xiàn)一個
TableViewModel
代理類
TableViewModel.h
@interface TableViewModel : NSObject <UITableViewDataSource, UITableViewDelegate>
@property (assign, nonatomic) NSInteger row;
- (void)initModelWithTableView:(UITableView *)tableView;
@end
TableViewModel.m
- (void)initModelWithTableView:(UITableView *)tableView {
tableView.delegate = self;
tableView.dataSource = self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return (self.row > 0) ? self.row : 8;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 20;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.textLabel.text = [NSString stringWithFormat:@"section -- %ld, row -- %ld", indexPath.section, indexPath.row];
cell.textLabel.textColor = [UIColor blueColor];
cell.backgroundColor = [UIColor lightGrayColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"didSelectRow -- %ld", indexPath.row);
}
@end
- 在控制器中創(chuàng)建
TableViewModel
類的屬性,防止調(diào)用一次之后被銷毀
@interface ViewController3 ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) TableViewModel *model;
@end
- 初始化
TableViewModel
類并將設置好的TableView
傳遞過去。
row
屬性僅僅為了舉例說明,使用時可以選擇通過多屬性或block
的方式將所需的值傳遞過去。
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"tableView" owner:self options:nil];
_tableView = [views lastObject];
[self.view addSubview:_tableView];
_model = [[TableViewModel alloc] init];
_model.row = 12;
[_model initModelWithTableView:_tableView];
}