灵活使用Category

我们常会见到这样的写法:

- (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;  
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容