iOS MVP架構(gòu)

?MVP 數(shù)據(jù)提供層,視圖層 都持有代理,實(shí)現(xiàn)雙向通訊

Model -> View 通訊

1. V 遵守 寫(xiě)要實(shí)現(xiàn)功能的代理,實(shí)現(xiàn)代理, 比如刷新視圖

2.確定調(diào)用者 即M的關(guān)聯(lián)類(lèi),屬性delegate,?

if (self.delegate && [self.delegate respondsToSelector:@selector(didClickNum:indexpath:)]) {

? ? ? ? [self.delegate didClickNum:self.numLabel.text indexpath:self.indexPath];

? ? }

View-> Model? 通訊 一樣的

MVC


MVC示意圖

V 持有 M

MVCTableViewCell?

// APP : MODEL -> UI

- (void)setModel:(Model *)model{

? ? _model? ? ? ? ? ? ? = model;

? ? self.numLabel.text? = model.num;

? ? self.nameLabel.text = model.name;

}

UI 改變,對(duì)應(yīng)的Model改變

- (void)setNum:(int)num{

? ? _num? ?= num;

? ? self.numLabel.text? = [NSString stringWithFormat:@"%d",self.num];

? ???_model.num = num

}

這樣V 持有 M,不符合低耦合原則

MVP架構(gòu),實(shí)現(xiàn)高內(nèi)聚,低耦合

V 和 M 之間的雙向通訊使用代理

V 做自己的事,比如刷新視圖

M 相關(guān)的類(lèi)做數(shù)據(jù)刷新

V ?-> M ?V通知M 做事改變Model,使用代理

M -> V ?M通知V 刷新視圖,使用代理


ViewController.m

// MVP 數(shù)據(jù)提供層,視圖層 都持有代理,實(shí)現(xiàn)雙向通訊

? ? // 數(shù)據(jù)提供層

? ? self.pt = [[Present2 alloc] init];? ??

? ? // 視圖層

? ? self.homeView = [[HomeView alloc] initWithFrame:self.view.bounds];

? ? // 將視圖層放在self.view中

? ? self.view = self.homeView;

?? ?

? ? // UI -> 數(shù)據(jù) 通訊,確定實(shí)現(xiàn)協(xié)議的類(lèi)

? ? self.homeView.pt = self.pt;

?? ?

? ? // 數(shù)據(jù) ->UI 通訊, 確定實(shí)現(xiàn)協(xié)議的類(lèi)

? ? self.pt.delegate = self.homeView;

?? ?

? ? // 加載頁(yè)面數(shù)據(jù)

? ? [self.pt loadUIData];


代理

@protocol?PresentDelegate?<NSObject>

-(void)reloadUI:(NSArray?*)datas;

- (void)didClickNum:(NSString?*)num?indexpath:(NSIndexPath?*)indexpath;

@end

數(shù)據(jù)提供層?Present

@interface Present2 : NSObject<Present2Delegate>

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, weak) id<Present2Delegate> delegate;

- (void)loadUIData;

@end


- (void)didClickNum:(NSString *)num indexpath:(NSIndexPath *)indexpath {

? ? if (indexpath.row < self.dataArray.count) {

? ? ? ? Model *model = self.dataArray[indexpath.row];

? ? ? ? model.num? ? = num;

? ? }

}

- (void)loadUIData {

? ? if (self.delegate && [self.delegate respondsToSelector:@selector(reloadUI:)]) {

? ? ? ? [self.delegate reloadUI:self.dataArray];

? ? }

}

?視圖層?HomeView

@interface HomeView : UIView<PresentDelegate>

@property (nonatomic, strong) Present?*pt;

@end

MVCTableViewCell?

Present?*pt 屬性傳遞過(guò)來(lái)

-(void)reloadUI:(NSArray *)datas {

? ? [self.dataSource addDataArray:datas];

? ? [self.tableView reloadData];

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容