?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

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];
}