我們常會見到這樣的寫法:
- (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;
}
這里可以運用分類進行重構:
為UITableView定義一個分類:
.h 聲明文件
@interface UITableView (dequeue)
- (UITableViewCell *)dequeueCellWithIdentifier: (NSString *)identifier;
@end
.m 實現文件
@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
使用的時候就是這樣:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueCellWithIdentifier: staticIdentifier];
//do something here
return cell;
}