CTMediator实践总结
需求
在 ViewController ,点击按钮跳向 A2ViewController ,并传参 name=我 (正向传值)
在 A2ViewController ,点击屏幕,跳回 ViewController ,并传参 city=北京 (反向传值)
基于CTMediator的组件化方案,有哪些核心组成?
-
CTMediator中间件:集成就可以了
-
模块Target_module:模块的实现及提供对外的方法调用Action_methodName,需要传参数时,都统一以NSDictionary*的形式传入。
-
CTMediator+module分类:扩展里声明了模块业务的对外接口,参数明确,这样外部调用者可以很容易理解如何调用接口。
导入三方库 CTMediator https://github.com/casatwy/CTMediator
创建 CTMediator 的分类
CTMediator+A.h
@interface CTMediator (A) - (UIViewController *)A2WithName:(NSString *)name callBack:(void (^) (NSDictionary *info))callBack; @end
CTMediator+A.m
@implementation CTMediator (A) - (UIViewController *)A2WithName:(NSString *)name callBack:(void (^) (NSDictionary *info))callBack{ NSMutableDictionary * parameters = [NSMutableDictionary dictionary]; parameters[@"name"] = name; parameters[@"callBack"] = callBack; return [self performTarget:@"A" action:@"A2" params:parameters shouldCacheTarget:NO]; } @end
创建 Target_A 对象
Target_A.h
@interface Target_A : NSObject - (UIViewController *)Action_A2:(NSDictionary *)parameters; @end
Target_A.m
@implementation Target_A - (UIViewController *)Action_A2:(NSDictionary *)parameters{ A2ViewController * secondVC = [A2ViewController new]; secondVC.name = parameters[@"name"]; secondVC.callBack = parameters[@"callBack"]; return secondVC; } @end
正向传值
UIViewController * vc = [[CTMediator sharedInstance] A2WithName:@"我" callBack:^(NSDictionary * _Nonnull info) { NSLog(@"回调了%@",info); }]; if (vc) { [self presentViewController:vc animated:YES completion:nil]; }
反向传值
@interface A2ViewController : UIViewController @property (nonatomic, copy) NSString * name; @property (nonatomic, copy) void (^callBack) (NSDictionary *info); @end
回调
if (self.callBack) { self.callBack(@{@"city":@"北京"}); } [self dismissViewControllerAnimated:YES completion:nil];
在北京的灯中,有一盏是我家的。这个梦何时可以实现?哪怕微微亮。北京就像魔鬼训练营,有能力的留,没能力的走……