我在网上找到了一个例子,说明如何分离UITableview的数据源以使代码更加可重用。但是,在这段代码中,它使用一个块代替委托来更新单元。到目前为止,在我的项目中,我一直在使用代表以保持一致性,所以我希望它保持这种方式,所以如果有人能够解释更好的块并帮助我重构下面的示例代码以包含delegates
而不是该块,我很乐意。我使用的示例来自http://www.objc.io/issue-1/lighter-view-controllers.html;了解委托与区块。 (重构代码使用代表团而不是块)
//
// ArrayDataSource.h
// objc.io example project (issue #1)
//
#import <Foundation/Foundation.h>
typedef void (^TableViewCellConfigureBlock)(id cell, id item);
@interface ArrayDataSource : NSObject <UITableViewDataSource>
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;
- (id)itemAtIndexPath:(NSIndexPath *)indexPath;
@end
.M
//
// ArrayDataSource.h
// objc.io example project (issue #1)
//
#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
并对其在UIViewController
用法是;
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;
我尝试每天学习新的东西,如果有人能够帮助,这将是伟大的。有一天,我希望作为一个开发人员改进:)
我明白数据源的分离,但使用块而不是委托对我来说是新的(怪异的)。
非常感谢这是非常有帮助的。 :) – DevC 2014-09-11 12:36:20