4
if (cell == nil)
{
5
cell = [[[WHTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
6
}
7
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
8
cell.title
=
[[featuredArticles
objectAtIndex:indexPath.row]
objectForKey:@"title"];
9
return cell;
10 }
对此我们可以提取个公共的方法,并放置在一个适当的地方。
UITableViewCell 的 Category
应该是一个比较好的去处。重构后提取的方法以及实际调用的代码如下:
重构后
:
1
@implementation UITableViewCell(Cache)
2
+ (id)dequeOrCreateInTable:(UITableView*)tableView withId: (NSString*)reuseId
andStyle:(UITableViewCellStyle)style {
3
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
4
if (cell == nil) {
5
cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:reuseId]
autorelease];
6
}
7
return cell;
8
}
9
@end
10
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath {
11
UITableViewCell *cell = [UITableViewCell dequeOrCreateInTable:tableView
withId:@"wikiHowCell" andStyle:UITableViewCellStyleDefault];
12
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
13
cell.title
=
[[featuredArticles
objectAtIndex:indexPath.row]
objectForKey:@"title"];
14
return cell;
15
}
从代码量衡量,仅从此处可能感觉重构前后变化不大,甚至还会略有增多。但如果考虑到公
用方法的多次使用产生的
“效益”,付出的努力应该是值当的!
提取方法以调整抽象层次
写代码有时和说话一样,要体现层次感,可能是首先罗列要点,然后再逐点细化。但如果时
而说要点,时而谈细节,就会造成听者理解上的障碍。如下的代码就会有这样的一个问题:
找软件资料,就到一览软件文库