在使用MVC架构模式书写代码的过程中,难免会遇到大量的代理方法写在控制器(C)里面,使得控制器代码异常庞大并且不便于阅读。
这种情况下可以选择将一部分代理方法代码抽到代理类里面,从而达到一定程度的优化。
如下是实现步骤代码:
- 实现一个
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
- 在控制器中创建
TableViewModel
类的属性,防止调用一次之后被销毁
@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];
}