不引入头文件使用文件内容的几种方式
项目解耦中碰到比较头疼的问题,就是文件引用问题,很多引用的文件并不属于当前模块,并且无法解耦到底层,有时候为了避免中间层之间的循环引用等等,引用文件的用途主要有如下几种情况。
1. 只是单纯的跳转到某个VC
Class cls = NSClassFromString(@"GuideInstalledViewController");
if (!cls) {
return;
}
UIViewController *vc = [[cls alloc] init];
[vc setValue:self.setDevPosModel.ssid forKey:@"ssid"];
[vc setValue:self.setDevPosModel.ssid5g forKey:@"ssid5g"];
[self.navigationController pushViewController:vc animated:YES];
借助NSClassFromString通过硬编码形式获取对应的类对象,再通过KVC的键值对方法对需要参数进行处理,实现我们的跳转需求。硬编码处理需要对转化的Class进行判断,防止该类删除了或改名,返回nil的情况。
2. 调用某个类的类方法
[[HWComponentMediator shareInstance] performTargerClass:@"HWHomeViewModel" actionName:@"getRouterCapability:" params:@[completionBlock]];
3. 调用某个类的实例方法
[[HWComponentMediator shareInstance] performAction:@"deviceCollectionViewDidSelectItemWithModelEx:"
target:rootVC
params:@[self.currentEntity]];
4. 调用单例的实例方法
[[HWComponentMediator shareInstance] performSingletonTarger:@"HWViewManagerService"
shareInstanceName:@"sharedInstance"
actionName:@"loadWifiExtenderHomeManageHandler"
params:nil];
针对情况2,3,4实现的思路是通过NSClassFromString生成对应的Class,然后在通过 NSInvocation消息转发机制,达到我们的要求。为了方便管理,已经把处理的过程封装出一个单独的类HWComponentMediator。详细的封装内容大家可以移步去HWComponentMediator查看具体代码实现。