Lighter ViewControllers

        ViewController 可能会是你的iOS项目文件中最大的文件,在大多数情况下,ViewController又是最难复用的。下面介绍几种方法来给ViewController瘦身。

  • 将数据源和协议从ViewController中分离
        例如,我们有个ViewController来配置UITableView的数据源和协议。TableView中的Cell负责显示各种水果照片和价格,另外一个项目的TableView的Cell负责显示各种景点的照片和景点历史,还有一个项目的Cell负责显示商品的照片跟评论和价格。

        我们最常用的做法就是把照片的URL和文字都存储在数组中,然后根据indexPath.row取数据赋给Cell。代码一般这么写:

# pragma mark Pragma 

- (Photo*)photoAtIndexPath:(NSIndexPath*)indexPath {
    return photos[(NSUInteger)indexPath.row];
}

- (NSInteger)tableView:(UITableView*)tableView 
 numberOfRowsInSection:(NSInteger)section {
    return photos.count;
}

- (UITableViewCell*)tableView:(UITableView*)tableView 
        cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    PhotoCell* cell = [tableView dequeueReusableCellWithIdentifier:PhotoCellIdentifier 
                                                      forIndexPath:indexPath];
    Photo* photo = [self photoAtIndexPath:indexPath];
    cell.label.text = photo.name;
    return cell;
}


        细想,这三个项目除了给Cell设置内容的方式,其他完全一样,还有必要在每个项目中都重复的写一遍配置数据的几个方法吗?

是否能将给数据源配置数据的这部分代码单独写成一个类(ArrayDataSource),凡事把TableView的数据存储在数组中的TableView,就不用每次都写这几个方法了,而是使用一行代码:self.tableView.dataSource = xxxArrayDataSource;

        这个DataSource类的三个方法需要什么呢?

  1. 存储数据的数组
  2. Cell的Identifier
  3. Cell的内容设置方式(文字是设置到label还是detialLabel)

        所以我们可以创建一个这样的DataSource类:

@implementation ArrayDataSource

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

- (NSInteger)tableView:(UITableView*)tableView 
 numberOfRowsInSection:(NSInteger)section {
    return items.count;
}

- (UITableViewCell*)tableView:(UITableView*)tableView 
        cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    id cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier
                                              forIndexPath:indexPath];
    id item = [self itemAtIndexPath:indexPath];
    configureCellBlock(cell,item);
    return cell;
}

@end

这个类的.h文件中需要有一个items数组,和configureCellBlock的block 还有一个 cellIdentifier字符串。当然还要创建一个init方法,需要把这单个参数传递进去。

         有了这个类,我们就不必在水果、景点、商城ViewController中写配置数据的代码了。我们可以这样写代码:

void (^configureCell)(PhotoCell*, Photo*) = ^(PhotoCell* cell, Photo* photo) {
   cell.label.text = photo.name;
};
photosArrayDataSource = [[ArrayDataSource alloc] initWithItems:photos
                                                cellIdentifier:PhotoCellIdentifier
                                            configureCellBlock:configureCell];
self.tableView.dataSource = photosArrayDataSource;


        当然也可以使用这种思想解决使用NSDiction存储数据的TableView的瘦身问题。


  • 将逻辑移动到Model中去

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值