一、在iOS开发中,MVC模式是再经典不过的了,本文将从tableview的使用以及自定义cell结合来感受MVC设计模式。
1、在ZPMainController.m文件中
(1)通过懒加载获取到模型数据,保存到数组helps中
<span style="font-size:18px;">/**
* 懒加载模型数据
*/
-(NSArray *)helps
{
if (_helps == nil) {
_helps = [ZPHelp helpArray];
}
return _helps;
}</span>
(2)然后只需要在viewDidLoad中调用这个方法
<span style="font-size:18px;">- (void)setupTableView
{
myBlock configureCell = ^(ZPTableViewCell *cell, ZPHelp *model) {
//使用分类方法
[cell setDataForCell:model];
};
self.ZPArrayDataSource = [[ZPTableViewDataSource alloc] initWithItemArray:self.helps identifier:ID block:configureCell];
self.tableView.dataSource = self.ZPArrayDataSource;
}</span>
2、在ZPTableViewDataSource类中
(1).h文件
/**
* 定义一个block,用于接收外界传入参数,内部处理
*
* @param cell tableview的cell
* @param item 模型数据对象
*/
typedef void (^myBlock)(id cell,id item);
//
重写
init
方法,拦截该类创建,做对应操作
- (instancetype)initWithItemArray:(NSArray *)itemArray identifier:(NSString *)identifier block:(myBlock)myBlock;
(2).m文件,实现数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.itemArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ZPTableViewCell *cell = [ZPTableViewCell cellWithTableView:tableView identifier:self.identifier];
ZPHelp *model = self.itemArr[indexPath.row];
//执行block中封装的自定义cell设置数据的方法
self.myBlock(cell,model);
return cell;
}
3、在自定义cell类.h文件中
//开放内部子控件,给外界模型设置属性值
@property(nonatomic ,weak)UILabel *titleL ;
@property(nonatomic ,weak)UILabel *urlL ;
@property(nonatomic ,weak)UILabel *IDL ;
/// 提供快速创建自定义cell的方法
+ (instancetype)cellWithTableView:(UITableView *)tableView identifier:(NSString *)identifier;
4、在自定义cell类的.h文件分类中
/// 给自定义的cell添加分类方法,设置cell内部属性
/// @param model 传递模型
- (void)setDataForCell:(ZPHelp *)model;
5、结合模型类ZPHelp,就可以完成M(model)- V(view)- C(controller)之间的数据传递,从而更新UI界面。
二、总结:
1、很大程度上减少了控制器的负担,可以更专心处理业务逻辑
2、符合MVC模式真正原则,model只负责处理数据,view只负责显示数据,controller负责处理业务逻辑
3、优化代码结构,结构清晰,符合面向对象的封装思想。
【by:Leo_zzp,支持原创,转载请说明出处!】
个人邮箱:15999745308@163.com,GitHub链接:MrLeoZou,期待您的交流!