MVC下分离tableView的Datasource
封装一个继承与NSObject的ArrayDataSource类来专门处理tableView的数据
代码如下:
ArrayDataSource.h中
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef void (^TableViewCellConfigureBlock)(id cell, id item);
@interface ArrayDataSource : NSObject <UITableViewDataSource>
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;
//用于取出当前Cell的model
- (id)itemAtIndexPath:(NSIndexPath *)indexPath;
@end
ArrayDataSource.m中
#import "ArrayDataSource.h"
@interface ArrayDataSource ()
@property (nonatomic, strong) NSArray *items;
@property (nonatomic, copy) NSString *cellIdentifier;
@property (nonatomic, copy) TableViewCellConfigureBlock configureCellBlock;
@end
@implementation ArrayDataSource
- (id)init
{
return nil;
}
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock
{
self = [super init];
if (self) {
self.items = anItems;
self.cellIdentifier = aCellIdentifier;
self.configureCellBlock = [aConfigureCellBlock copy];
}
return self;
}
- (id)itemAtIndexPath:(NSIndexPath *)indexPath
{
return self.items[(NSUInteger) indexPath.row];
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier
forIndexPath:indexPath];
id item = [self itemAtIndexPath:indexPath];
self.configureCellBlock(cell, item);
return cell;
}
@end
实现代码:
static NSString * const PhotoCellIdentifier = @"PhotoCell";
- (void)setupTableView
{
TableViewCellConfigureBlock configureCell = ^(UITableViewCell *cell, NSString *str) {
cell.textLabel.text = str;
};
// Demo 中简单起见传的字符串, 一般是传Model的
NSArray *photos = @[@"jiang",@"yong",@"chang"];
self.photosArrayDataSource = [[ArrayDataSource alloc] initWithItems:photos
cellIdentifier:PhotoCellIdentifier
configureCellBlock:configureCell];
self.dataSource = self.photosArrayDataSource;
[self registerClass:[UITableViewCell class] forCellReuseIdentifier:PhotoCellIdentifier];
// [self.tableView registerNib:[PhotoCell nib] forCellReuseIdentifier:PhotoCellIdentifier];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *pasStr = [self.photosArrayDataSource itemAtIndexPath:indexPath];
if ([self.myDelegate respondsToSelector:@selector(passStrToController:)]) {
[self.myDelegate passStrToController:pasStr];
}
}
但是有一个问题###
Demo中把tableView和Controller分离了开来,导致处理数据
NSArray *photos = @[@"jiang",@"yong",@"chang"];
只能在tableView中赋值,
而不能从controller中传递过来
// NSArray *photos = self.dataArray;
原因:在初始化的时候已经给NSArray *photos赋值了, 而当时还没有传值,所以为空.