ViewController 可能会是你的iOS项目文件中最大的文件,在大多数情况下,ViewController又是最难复用的。下面介绍几种方法来给ViewController瘦身。
- 将数据源和协议从ViewController中分离
我们最常用的做法就是把照片的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类的三个方法需要什么呢?
- 存储数据的数组
- Cell的Identifier
- 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中去