我們常會(huì)見到這樣的寫法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//do something here
return cell;
}
這里可以運(yùn)用分類進(jìn)行重構(gòu):
為UITableView定義一個(gè)分類:
.h 聲明文件
@interface UITableView (dequeue)
- (UITableViewCell *)dequeueCellWithIdentifier: (NSString *)identifier;
@end
.m 實(shí)現(xiàn)文件
@implementation UITableView (dequeue)
- (UITableViewCell *)dequeueCellWithIdentifier: (NSString *)identifier {
static NSString *cellIdentifier = identifier;
UITableViewCell *cell = [self dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
return cell;
}
@end
使用的時(shí)候就是這樣:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueCellWithIdentifier: staticIdentifier];
//do something here
return cell;
}