今天我們講述一個知識點(大家可能遺漏的)
多態是面試程序設計(OOP)一個重要特征,但在iOS中,可能比較少的人會留意這個特征,實際上在開發中我們可能已經不經意的使用了多態。比如說:
有一個tableView,它有多種cell,cell的UI差距較大,但是他們的model類型又都是一樣的。由於這幾種的cell都具有相同類型的model,那么肯定先創建一個基類cell,如:
@interface BaseCell : UITableViewCell @property (nonatomic, strong) Model *model; @end
然后各種cell繼承自這個基類cell
紅綠藍三種子類cell如下類似
@interface BaseCell : UITableViewCell @property (nonatomic, strong) Model *model; @end
子類cell重寫BaseCell的setModel方法
// 重寫父類的setModel:方法 - (void)setModel:(Model *)model { // 調用父類的setModel:方法 super.model = model; // do something... }
在Controller中
// cell復用ID array - (NSArray *)cellReuseIdArray { if (!_cellReuseIdArray) { _cellReuseIdArray = @[RedCellReuseID, GreenCellReuseID, BlueCellReuseID]; } return _cellReuseIdArray; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellResueID = nil; cellResueID = self.cellReuseIdArray[indexPath.section]; // 父類 BaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellResueID]; // 創建不同的子類 if (!cell) { switch (indexPath.section) { case 0: // 紅 { // 父類指針指向子類 cell = [[RedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID]; } break; case 1: // 綠 { // 父類指針指向子類 cell = [[GreenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID]; } break; case 2: // 藍 { // 父類指針指向子類 cell = [[BlueCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellResueID]; } break; } } // 這里會調用各個子類的setModel:方法 cell.model = self.dataArray[indexPath.row]; return cell; }
這個在我本身的代碼里面也會有,其實這里面也用了類的多態性。
一句話概括多態:子類重寫父類的方法,父類指針指向子類。
多態的三個條件
- 繼承:各種cell繼承自BaseCell
- 重寫:子類cell重寫BaseCell的set方法
- 父類cel指針指向子類cell
以上就是多態在實際開發中的簡單應用,合理使用多態可以降低代碼的耦合度,可以讓代碼更易拓展。
