本文主要介绍组件化通讯的三种方式
URL路由 ---- MGJRouter
基于URL匹配或者命名约定,通过runtime动态调用,实现简单,类似系统的openURL
优点
- 极高的动态性
- 可以统一管理多平台的路由规则
- 可以适配 URL Scheme
缺点
- 参数通过字符串形式转换,方式有限,编译期无法进行类型检测
- 参数格式不明确
- 不支持Storyboard
- 无法保证使用模块一定存在
- 解耦能力有限,url字符串一旦修改会导致其他地方失效
MGJRouter
- App启动时实例化所需的组件模块,注册
url
- 需要调用其他模块时,传递
url
和参数,类似系统的openURL
//注册url
[MGJRouter registerURLPattern:@"mgj://category/travel" toHandler:^(NSDictionary *routerParameters) {
NSLog(@"routerParameters == %@",routerParameters);
}];
//调用路由
[MGJRouter openURL:@"mgj://category/travel" withUserInfo:@{@"user_id": @1900} completion:nil];
Target-Action -- CTMediator
基于runtime和category特性,动态获取模块,例如通过NSClassFromString
获取实例,performSelector + NSInvocation
动态调用方法
- 利用分类添加路由接口,通过字符串获取对应的类
- 通过runtime创建实例,动态调用方法
优点
- 通过
category
明确接口声明 轻量
缺点
- 模块化繁琐,需要在
target、mediator
重新添加每个接口 -
category
中通过字符串识别,存在和URL路由一样的问题 - 无法保证使用的模块一定存在,target修改后,运行时才能报错
CTMediator
在分类中通过调用performTarget:action:params:shouldCacheTarget:
方法,找到对应的target
和action
- (id)performTarget:(NSString *)targetName action:(NSString *)actionName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget
{
if (targetName == nil || actionName == nil) {
return nil;
}
//在swift中使用时,需要传入对应项目的target名称,否则会找不到视图控制器
NSString *swiftModuleName = params[kCTMediatorParamsKeySwiftTargetModuleName];
// generate target 生成target
NSString *targetClassString = nil;
if (swiftModuleName.length > 0) {
//swift中target文件名拼接
targetClassString = [NSString stringWithFormat:@"%@.Target_%@", swiftModuleName, targetName];
} else {
//OC中target文件名拼接
targetClassString = [NSString stringWithFormat:@"Target_%@", targetName];
}
//缓存中查找target
NSObject *target = [self safeFetchCachedTarget:targetClassString];
//缓存中没有target
if (target == nil) {
//通过字符串获取对应的类
Class targetClass = NSClassFromString(targetClassString);
//创建实例
target = [[targetClass alloc] init];
}
// generate action 生成action方法名称
NSString *actionString = [NSString stringWithFormat:@"Action_%@:", actionName];
//通过方法名字符串获取对应的sel
SEL action = NSSelectorFromString(actionString);
if (target == nil) {
// 这里是处理无响应请求的地方之一,这个demo做得比较简单,如果没有可以响应的target,就直接return了。实际开发过程中是可以事先给一个固定的target专门用于在这个时候顶上,然后处理这种请求的
[self NoTargetActionResponseWithTargetString:targetClassString selectorString:actionString originParams:params];
return nil;
}
//是否需要缓存
if (shouldCacheTarget) {
[self safeSetCachedTarget:target key:targetClassString];
}
//是否响应sel
if ([target respondsToSelector:action]) {
//动态调用方法
return [self safePerformAction:action target:target params:params];
} else {
// 这里是处理无响应请求的地方,如果无响应,则尝试调用对应target的notFound方法统一处理
SEL action = NSSelectorFromString(@"notFound:");
if ([target respondsToSelector:action]) {
return [self safePerformAction:action target:target params:params];
} else {
// 这里也是处理无响应请求的地方,在notFound都没有的时候,这个demo是直接return了。实际开发过程中,可以用前面提到的固定的target顶上的。
[self NoTargetActionResponseWithTargetString:targetClassString selectorString:actionString originParams:params];
@synchronized (self) {
[self.cachedTarget removeObjectForKey:targetClassString];
}
return nil;
}
}
}
-
safePerformAction:target:params:
方法的实现,是通过NSInvocation
进行消息转发+参数传递
- (id)safePerformAction:(SEL)action target:(NSObject *)target params:(NSDictionary *)params
{
//获取方法签名
NSMethodSignature* methodSig = [target methodSignatureForSelector:action];
if(methodSig == nil) {
return nil;
}
//判断返回类型,根据返回值完成参数传递
const char* retType = [methodSig methodReturnType];
//void类型
if (strcmp(retType, @encode(void)) == 0) {
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setArgument:¶ms atIndex:2];
[invocation setSelector:action];
[invocation setTarget:target];
[invocation invoke];
return nil;
}
//NSInteger类型
if (strcmp(retType, @encode(NSInteger)) == 0) {
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setArgument:¶ms atIndex:2];
[invocation setSelector:action];
[invocation setTarget:target];
[invocation invoke];
NSInteger result = 0;
[invocation getReturnValue:&result];
return @(result);
}
//BOOL类型
if (strcmp(retType, @encode(BOOL)) == 0) {
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setArgument:¶ms atIndex:2];
[invocation setSelector:action];
[invocation setTarget:target];
[invocation invoke];
BOOL result = 0;
[invocation getReturnValue:&result];
return @(result);
}
//CGFloat类型
if (strcmp(retType, @encode(CGFloat)) == 0) {
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setArgument:¶ms atIndex:2];
[invocation setSelector:action];
[invocation setTarget:target];
[invocation invoke];
CGFloat result = 0;
[invocation getReturnValue:&result];
return @(result);
}
//NSUInteger类型
if (strcmp(retType, @encode(NSUInteger)) == 0) {
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
[invocation setArgument:¶ms atIndex:2];
[invocation setSelector:action];
[invocation setTarget:target];
[invocation invoke];
NSUInteger result = 0;
[invocation getReturnValue:&result];
return @(result);
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
return [target performSelector:action withObject:params];
#pragma clang diagnostic pop
}
Protocol Class -- BeeHive
- 将
protocol
和对应的类
字典匹配 - 通过
protocol
获取class
动态创建
优点
- 通过接口调用,保证参数类型安全
- 直接使用
protocol
接口,无需重复封装
缺点
- 不支持swift
- 无法保证使用的Protocol一定存在对应模块
- 通过框架创建所有对象,不支持外部传入参数
BeeHive
BeeHive
借鉴了Spring Service、Apache DSO的架构理念,采用AOP+扩展Application API
形式,将业务
和基础功能
通过模块方法解耦,模块直接通过Service
形式调用,避免直接依赖,在AppDelegate
中解耦,进行逻辑拆分,每个模块微应用形式独立存在
BeeHive 注册
BeeHive
通过BHModuleManager
来管理已经被注册的模块
BeeHive
提供了三种注册方法:.plist
、动态注册(load)
、Annotation
.plist文件
- 设置
plist文件路径
[BHContext shareInstance].moduleConfigName = @"BeeHive.bundle/BeeHive";//可选,默认为BeeHive.bundle/BeeHive.plist
-
创建
plist文件
loadLocalModules
方法读取plist
文件,添加到BHModuleInfos
数组
#pragma mark - Private
//初始化context,加载Modules、Services
-(void)setContext:(BHContext *)context
{
_context = context;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self loadStaticServices];
[self loadStaticModules];
});
}
//加载modules
- (void)loadStaticModules
{
// 读取本地plist文件里面的Module,并注册到BHModuleManager的BHModuleInfos数组中
[[BHModuleManager sharedManager] loadLocalModules];
//注册所有modules,在内部根据优先级进行排序
[[BHModuleManager sharedManager] registedAllModules];
}
- (void)loadLocalModules
{
//plist文件路径
NSString *plistPath = [[NSBundle mainBundle] pathForResource:[BHContext shareInstance].moduleConfigName ofType:@"plist"];
//判断文件是否存在
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
return;
}
//读取整个文件[@"moduleClasses" : 数组]
NSDictionary *moduleList = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
//通过moduleClasses key读取 数组 [[@"moduleClass":"aaa", @"moduleLevel": @"bbb"], [...]]
NSArray<NSDictionary *> *modulesArray = [moduleList objectForKey:kModuleArrayKey];
NSMutableDictionary<NSString *, NSNumber *> *moduleInfoByClass = @{}.mutableCopy;
//遍历数组
[self.BHModuleInfos enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[moduleInfoByClass setObject:@1 forKey:[obj objectForKey:kModuleInfoNameKey]];
}];
[modulesArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (!moduleInfoByClass[[obj objectForKey:kModuleInfoNameKey]]) {
//存储到 BHModuleInfos 中
[self.BHModuleInfos addObject:obj];
}
}];
}
动态注册(load)
- 在
load
方法中注册
+ (void)load
{
[BeeHive registerDynamicModule:[self class]];
}
-
registerDynamicModule
方法
+ (void)registerDynamicModule:(Class)moduleClass
{
[[BHModuleManager sharedManager] registerDynamicModule:moduleClass];
}
- (void)registerDynamicModule:(Class)moduleClass
{
[self registerDynamicModule:moduleClass shouldTriggerInitEvent:NO];
}
- (void)registerDynamicModule:(Class)moduleClass
shouldTriggerInitEvent:(BOOL)shouldTriggerInitEvent
{
[self addModuleFromObject:moduleClass shouldTriggerInitEvent:shouldTriggerInitEvent];
}
- 或者通过宏定义
BH_EXPORT_MODULE
代替load
方法
#define BH_EXPORT_MODULE(isAsync) \
+ (void)load { [BeeHive registerDynamicModule:[self class]]; } \
-(BOOL)async { return [[NSString stringWithUTF8String:#isAsync] boolValue];}
Annotation注册
- 通过
BeeHiveMod
的宏进行Annotation
标记
//***** 使用
BeeHiveMod(ShopModule)
//***** BeeHiveMod的宏定义
#define BeeHiveMod(name) \
class BeeHive; char * k##name##_mod BeeHiveDATA(BeehiveMods) = ""#name"";
//***** BeeHiveDATA的宏定义
#define BeeHiveDATA(sectname) __attribute((used, section("__DATA,"#sectname" ")))
//***** 全部转换出来后为下面的格式
char * kShopModule_mod __attribute((used, section("__DATA,""BeehiveMods"" "))) = """ShopModule""";
__attribute
第一个参数
used
:用来修饰函数,被修饰后,意味着即使函数没有被引用,在Release下也不会被优化section("__DATA,""BeehiveMods"" ")
:指定未被优化的模块注入Mach-o
的__DATA
段BHReadConfiguration
方法读取Mach-o
中的数据段,取出存放到数组
NSArray<NSString *>* BHReadConfiguration(char *sectionName,const struct mach_header *mhp)
{
NSMutableArray *configs = [NSMutableArray array];
unsigned long size = 0;
#ifndef __LP64__
// 找到之前存储的数据段(Module找BeehiveMods段 和 Service找BeehiveServices段)的一片内存
uintptr_t *memory = (uintptr_t*)getsectiondata(mhp, SEG_DATA, sectionName, &size);
#else
const struct mach_header_64 *mhp64 = (const struct mach_header_64 *)mhp;
uintptr_t *memory = (uintptr_t*)getsectiondata(mhp64, SEG_DATA, sectionName, &size);
#endif
unsigned long counter = size/sizeof(void*);
// 把特殊段里面的数据都转换成字符串存入数组中
for(int idx = 0; idx < counter; ++idx){
char *string = (char*)memory[idx];
NSString *str = [NSString stringWithUTF8String:string];
if(!str)continue;
BHLog(@"config = %@", str);
if(str) [configs addObject:str];
}
return configs;
}
BeeHive模块事件
BeeHive给每个模块提供Application
生命周期事件,用于与主程序进行必要信息交互,感知模块生命周期的变化。
所有的Module
必须遵守BHModuleProtocol
协议,否则无法接受事件消息
在BHModuleManager
中,所有时间被定义成枚举BHModuleEventType
typedef NS_ENUM(NSInteger, BHModuleEventType)
{
//设置Module模块
BHMSetupEvent = 0,
//用于初始化Module模块,例如环境判断,根据不同环境进行不同初始化
BHMInitEvent,
//用于拆除Module模块
BHMTearDownEvent,
BHMSplashEvent,
BHMQuickActionEvent,
BHMWillResignActiveEvent,
BHMDidEnterBackgroundEvent,
BHMWillEnterForegroundEvent,
BHMDidBecomeActiveEvent,
BHMWillTerminateEvent,
BHMUnmountEvent,
BHMOpenURLEvent,
BHMDidReceiveMemoryWarningEvent,
BHMDidFailToRegisterForRemoteNotificationsEvent,
BHMDidRegisterForRemoteNotificationsEvent,
BHMDidReceiveRemoteNotificationEvent,
BHMDidReceiveLocalNotificationEvent,
BHMWillPresentNotificationEvent,
BHMDidReceiveNotificationResponseEvent,
BHMWillContinueUserActivityEvent,
BHMContinueUserActivityEvent,
BHMDidFailToContinueUserActivityEvent,
BHMDidUpdateUserActivityEvent,
BHMHandleWatchKitExtensionRequestEvent,
BHMDidCustomEvent = 1000
};
-
系统事件
:Application生命周期
通过将项目的AppDelegate
继承BHAppDelegate
@interface TestAppDelegate : BHAppDelegate <UIApplicationDelegate>
-
应用事件
:官方给出的流程图,其中modSetup、modInit等,可以用于编码实现各插件模块的设置与初始化。
自定义事件
:可以通过调用BHModuleManager
的triggerEvent :
方法处理所有事件
- (void)triggerEvent:(NSInteger)eventType
{
[self triggerEvent:eventType withCustomParam:nil];
}
- (void)triggerEvent:(NSInteger)eventType
withCustomParam:(NSDictionary *)customParam {
[self handleModuleEvent:eventType forTarget:nil withCustomParam:customParam];
}
#pragma mark - module protocol
- (void)handleModuleEvent:(NSInteger)eventType
forTarget:(id<BHModuleProtocol>)target
withCustomParam:(NSDictionary *)customParam
{
switch (eventType) {
//初始化事件
case BHMInitEvent:
//special
[self handleModulesInitEventForTarget:nil withCustomParam :customParam];
break;
//析构事件
case BHMTearDownEvent:
//special
[self handleModulesTearDownEventForTarget:nil withCustomParam:customParam];
break;
//其他3类事件
default: {
NSString *selectorStr = [self.BHSelectorByEvent objectForKey:@(eventType)];
[self handleModuleEvent:eventType forTarget:nil withSeletorStr:selectorStr andCustomParam:customParam];
}
break;
}
}
从上面代码发现,除了BHMInitEvent
初始化、BHMTearDownEvent
析构两个特殊事件外,所有的事件都是调用handleModuleEvent:forTarget:withSeletorStr:andCustomParam:
,在内部通过遍历moduleInstances
数组,调用performSelector:withObject:
实现
- (void)handleModuleEvent:(NSInteger)eventType
forTarget:(id<BHModuleProtocol>)target
withSeletorStr:(NSString *)selectorStr
andCustomParam:(NSDictionary *)customParam
{
BHContext *context = [BHContext shareInstance].copy;
context.customParam = customParam;
context.customEvent = eventType;
if (!selectorStr.length) {
selectorStr = [self.BHSelectorByEvent objectForKey:@(eventType)];
}
SEL seletor = NSSelectorFromString(selectorStr);
if (!seletor) {
selectorStr = [self.BHSelectorByEvent objectForKey:@(eventType)];
seletor = NSSelectorFromString(selectorStr);
}
NSArray<id<BHModuleProtocol>> *moduleInstances;
if (target) {
moduleInstances = @[target];
} else {
moduleInstances = [self.BHModulesByEvent objectForKey:@(eventType)];
}
//遍历 moduleInstances 实例数组,调用performSelector:withObject:方法实现对应方法调用
[moduleInstances enumerateObjectsUsingBlock:^(id<BHModuleProtocol> moduleInstance, NSUInteger idx, BOOL * _Nonnull stop) {
if ([moduleInstance respondsToSelector:seletor]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
//进行方法调用
[moduleInstance performSelector:seletor withObject:context];
#pragma clang diagnostic pop
[[BHTimeProfiler sharedTimeProfiler] recordEventTime:[NSString stringWithFormat:@"%@ --- %@", [moduleInstance class], NSStringFromSelector(seletor)]];
}
}];
}
3、BeeHive模块调用
通过BHServiceManager
来管理已经注册的Protocol
注册Protocol
的方式和注册Module
方式一一对应
.plist文件
- 设置
plist文件路径
[BHContext shareInstance].serviceConfigName = @"BeeHive.bundle/BHService";
- 创建
plist文件
-
loadStaticServices
方法读取plist
文件,存储到字典中
#pragma mark - Private
//初始化context,加载Modules、Services
-(void)setContext:(BHContext *)context
{
_context = context;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self loadStaticServices];
[self loadStaticModules];
});
}
//加载Services
-(void)loadStaticServices
{
[BHServiceManager sharedManager].enableException = self.enableException;
[[BHServiceManager sharedManager] registerLocalServices];
}
- (void)registerLocalServices
{
NSString *serviceConfigName = [BHContext shareInstance].serviceConfigName;
//plist文件路径
NSString *plistPath = [[NSBundle mainBundle] pathForResource:serviceConfigName ofType:@"plist"];
if (!plistPath) {
return;
}
NSArray *serviceList = [[NSArray alloc] initWithContentsOfFile:plistPath];
[self.lock lock];
//遍历并存储到allServicesDict中
for (NSDictionary *dict in serviceList) {
NSString *protocolKey = [dict objectForKey:@"service"];
NSString *protocolImplClass = [dict objectForKey:@"impl"];
if (protocolKey.length > 0 && protocolImplClass.length > 0) {
[self.allServicesDict addEntriesFromDictionary:@{protocolKey:protocolImplClass}];
}
}
[self.lock unlock];
}
动态注册(load)
- 在
load
方法中注册Protocol
协议,通过调用BeeHive里面的registerService:service:
方法完成注册
+ (void)load
{
[[BeeHive shareInstance] registerService:@protocol(UserTrackServiceProtocol) service:[BHUserTrackViewController class]];
}
👇
- (void)registerService:(Protocol *)proto service:(Class) serviceClass
{
[[BHServiceManager sharedManager] registerService:proto implClass:serviceClass];
}
Annotation注册
//****** 1、通过BeeHiveService宏进行Annotation标记
BeeHiveService(HomeServiceProtocol,BHViewController)
//****** 2、宏定义
#define BeeHiveService(servicename,impl) \
class BeeHive; char * k##servicename##_service BeeHiveDATA(BeehiveServices) = "{ \""#servicename"\" : \""#impl"\"}";
//****** 3、转换后的格式,也是将其存储到特殊的段
char * kHomeServiceProtocol_service __attribute((used, section("__DATA,""BeehiveServices"" "))) = "{ \"""HomeServiceProtocol""\" : \"""BHViewController""\"}";
获取Protocol
Protocol
相比Module
,可以返回Protocol实例对象
- (id)createService:(Protocol *)proto;
{
return [[BHServiceManager sharedManager] createService:proto];
}
👇
- (id)createService:(Protocol *)service
{
return [self createService:service withServiceName:nil];
}
👇
- (id)createService:(Protocol *)service withServiceName:(NSString *)serviceName {
return [self createService:service withServiceName:serviceName shouldCache:YES];
}
👇
- (id)createService:(Protocol *)service withServiceName:(NSString *)serviceName shouldCache:(BOOL)shouldCache {
if (!serviceName.length) {
serviceName = NSStringFromProtocol(service);
}
id implInstance = nil;
//判断protocol是否已经注册过
if (![self checkValidService:service]) {
if (self.enableException) {
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"%@ protocol does not been registed", NSStringFromProtocol(service)] userInfo:nil];
}
}
NSString *serviceStr = serviceName;
//如果有缓存,则直接从缓存中获取
if (shouldCache) {
id protocolImpl = [[BHContext shareInstance] getServiceInstanceFromServiceName:serviceStr];
if (protocolImpl) {
return protocolImpl;
}
}
//获取类后,然后响应下层的方法
Class implClass = [self serviceImplClass:service];
if ([[implClass class] respondsToSelector:@selector(singleton)]) {
if ([[implClass class] singleton]) {
if ([[implClass class] respondsToSelector:@selector(shareInstance)])
//创建单例对象
implInstance = [[implClass class] shareInstance];
else
//创建实例对象
implInstance = [[implClass alloc] init];
if (shouldCache) {
//缓存
[[BHContext shareInstance] addServiceWithImplInstance:implInstance serviceName:serviceStr];
return implInstance;
} else {
return implInstance;
}
}
}
return [[implClass alloc] init];
}
创建service之前,会检查Protocol是否注册过
从字典中取出Protocol对应的Class
如果实现了
singleton
方法实现了
shareInstance
,创建单例否则创建实例对象
将
implInstance
和serviceStr
缓存创建实例对象
serviceImplClass
方法中,protocol为key,serviceImp为value存在字典中
- (Class)serviceImplClass:(Protocol *)service
{
//通过字典将 协议 和 类 绑定,其中协议作为key,serviceImp(类的名字)作为value
NSString *serviceImpl = [[self servicesDict] objectForKey:NSStringFromProtocol(service)];
if (serviceImpl.length > 0) {
return NSClassFromString(serviceImpl);
}
return nil;
}
辅助类
BHConfig
:单例,维护一些动态的环境变量,作为BHContext
的补充BHContext
:单例,内部两个字典属性:modulesByName
、servicesByName
,用来保存上下文信息BHTimeProfiler
:计算时间性能方面的BHWatchDog
:新开一个线程,监听主线程是否堵塞