溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

iPhone開(kāi)發(fā)重構(gòu):提取公用的方法以清理重復(fù)代碼

發(fā)布時(shí)間:2020-04-23 13:50:25 來(lái)源:網(wǎng)絡(luò) 閱讀:1207 作者:benjielin 欄目:開(kāi)發(fā)技術(shù)

     無(wú)論在iPhone開(kāi)發(fā)還是學(xué)習(xí)的過(guò)程中都會(huì)看到一些不是很理想的代碼,不可否認(rèn)自己也在不斷“貢獻(xiàn)”著這類(lèi)代碼。面對(duì)一些代碼的“壞味道”,重構(gòu)顯然是個(gè)有效的解決途徑。《iPhone開(kāi)發(fā)重構(gòu)》系列就想總結(jié)和補(bǔ)充iPhone開(kāi)發(fā)中經(jīng)歷的一些重構(gòu),其間可能會(huì)引用一些開(kāi)源以及實(shí)際項(xiàng)目的代碼,本著對(duì)技術(shù)的探求,冒昧之處還請(qǐng)作者多多見(jiàn)諒。

 

   代碼重復(fù)是一個(gè)比較明顯的“壞味道”,提取公用的方法就是解決的途徑之一。iPhone開(kāi)發(fā)中,使用UITableView的時(shí)候就有如下一段“經(jīng)典”的模板代碼,因?yàn)檫@是項(xiàng)目模板自動(dòng)生成的,所以很多人就自然接受了。但隨著越來(lái)越多地通過(guò)copy&paste在一個(gè)項(xiàng)目中使用這段代碼,大家是否有些采取行動(dòng)的壓力呢?好吧,我們就從這“動(dòng)刀”吧!

 

重構(gòu)前:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"wikiHowCell";
    UITableViewCell *cell = (WHTableViewCell *)[tv dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[WHTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.title = [[featuredArticles objectAtIndex:indexPath.row] objectForKey:@"title"];
    return cell;
}

 

   對(duì)此我們可以提取個(gè)公共的方法,并放置在一個(gè)適當(dāng)?shù)牡胤?。UITableViewCell的Category應(yīng)該是一個(gè)比較好的去處。重構(gòu)后提取的方法以及實(shí)際調(diào)用的代碼如下:

重構(gòu)后:

@implementation UITableViewCell(Cache)

+ (id)dequeOrCreateInTable:(UITableView*)tableView withId: (NSString*)reuseId andStyle:(UITableViewCellStyle)style {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:reuseId] autorelease];
    }
    return cell;
}

@end

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [UITableViewCell dequeOrCreateInTable:tableView withId:@"wikiHowCell" andStyle:UITableViewCellStyleDefault];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.title = [[featuredArticles objectAtIndex:indexPath.row] objectForKey:@"title"];
    return cell;
}

   從代碼量衡量,僅從此處可能感覺(jué)重構(gòu)前后變化不大,甚至還會(huì)略有增多。但如果考慮到公用方法的多次使用產(chǎn)生的“效益”,付出的努力應(yīng)該是值當(dāng)?shù)模?/p>

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI