iOS DataSource从tableview分离 简化viewController

通过分离dataSource 让我们的code具有更高的复用性.

转载自汪海的实验室

定义dataSource

dataSource.h

typedef void (^TableViewCellConfigureBlock)(id cell, id item);

@interface GroupNotificationDataSource : NSObject<UITableViewDataSource>

- (id)initWithItems:(NSArray *)anItems cellIdentifier:(NSString *)aCellIdentifier configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;

- (id)itemAtIndexPath:(NSIndexPath *)indexPath;

@end

dataSource.m

@implementation GroupNotificationDataSource
{
    NSArray     *_itemsArray;
    NSString    *_cellIdentifier;
    TableViewCellConfigureBlock _configureCellBlock;
}

- (id)init{
    return nil;
}

- (id)initWithItems:(NSArray *)anItems cellIdentifier:(NSString *)aCellIdentifier configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock{
    self = [super init];
    if (self) {
        _itemsArray = anItems;
        _cellIdentifier = aCellIdentifier;
        _configureCellBlock = [aConfigureCellBlock copy];
    }
    return self;
}

- (id)itemAtIndexPath:(NSIndexPath *)indexPath {
    return _itemsArray[(NSUInteger) indexPath.row];
}

#pragma mark tableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _itemsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // NOTE: This method can return nil so you need to account for that in code 
    GroupNotificationCell *cell=[tableView dequeueReusableCellWithIdentifier:_cellIdentifier];
    // NOTE: Add some code like this to create a new cell if there are none to reuse
    if (cell==nil) {
        cell=[[GroupNotificationCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:_cellIdentifier];
    }
    id item = [self itemAtIndexPath:indexPath];
    _configureCellBlock(cell, item);
    return cell;
}

其中,需要注意tableView:cellForRowAtIndexPath:方法中对于cell的重用

重写cell的初始化

cell.h

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;

cell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self configureUI];
    }
    return self;
}

controller中设置tableview的dataSource

_dataSource=[[GroupNotificationDataSource alloc]initWithItems:[NSArray arrayWithObjects:@"1",@"2", nil] cellIdentifier:CellIdentifier configureCellBlock:^(id cell, id item) {
        //
    }];
    _tableview.dataSource=_dataSource;

需要注意的是_dataSource应该是成员变量,而非局部变量,否则会报错:message send to delloced object

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值