靈活使用Category

我們常會(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;  
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容