【iOS开发】深入MVC---UITableView的数据源方法封装

一、在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,期待您的交流!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值