iOS 组件化

基础模块 -> 通用模块 -> 业务模块

只能上层对下层依赖,项⽬公共代码资源 下沉,横向的依赖 最好下沉

组件化需求:

模块间解耦

模块重⽤

提⾼团队协作开发效率

单元测试 

不需要组件化:

项⽬较⼩,模块间交互简单,耦合少

模块没有被多个外部模块引⽤,只是⼀个单独的⼩模块

模块不需要重⽤,代码也很少被修改 

团队规模很⼩

组件化项目

Cocopods 实现组件化

pod lib create xxx

创建CommonUIModule模块

模块示意图

CommonUIModule -> Assets 图片和资源

CommonUIModule -> Classes 代码

Example  CommonUIModule使用案例

Podfile 文件 -> pod install

引用CommonUIModule本身模块,

引用其他模块 MacroAndCategoryModule

use_frameworks!

platform :ios, '9.0'

target 'CommonUIModule_Example' do

  pod 'CommonUIModule', :path => '../'

  pod 'MacroAndCategoryModule', :path => '../../MacroAndCategoryModule'

...

end

引用Cocopods 线上库

Development Pods -> Pod -> CommonUIModule.podspec

三方库

自身模块使用图片

1.打开 resource           

2. pathForResource 读取资源

NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"Home_TableView_Response_%@", channelId] ofType:@"json"];

    NSData*data = [NSDatadataWithContentsOfFile:path];

主模块读取子模块的 图片和资源

1.打开 resource

2. pathForResource 读取资源

NSString *bundlePath = [[NSBundle bundleForClass:[self class]].resourcePath stringByAppendingPathComponent:@"/LGHomeModule.bundle"];

NSBundle*resoure_bundle = [NSBundlebundleWithPath:bundlePath];

    [UIImage imageNamed:@"" inBundle:resoure_bundle withConfiguration:nil];

CTMediator 模块之间解耦

CTMediator示例图

Actions 响应者

Target_A.h 以Target_开头的

Target_A -> DemoModuleADetailViewController

中间层CTMediator

本地组件调用入口

- (id_Nullable)performTarget:(NSString *_Nullable)targetName action:(NSString *_Nullable)actionName params:(NSDictionary*_Nullable)params

targetClassString = [NSStringstringWithFormat:@"Target_%@", targetName];

Class targetClass = NSClassFromString(targetClassString);

 target = [[targetClass alloc] init];

NSString*actionString = [NSString stringWithFormat:@"Action_%@:", actionName];

SEL action =NSSelectorFromString(actionString);

[self safePerformAction:action target:target params:params]

方法执行: 快速转发 或 performSelector

- (id)safePerformAction:(SEL)actiontarget:(NSObject*)targetparams:(NSDictionary*)params

{

    NSMethodSignature * methodSig = [target methodSignatureForSelector:action];

    if(methodSig ==nil) {

        returnnil;

    }

    constchar* retType = [methodSigmethodReturnType];

    if(strcmp(retType,@encode(void)) ==0) {

        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];

        [invocation setArgument:¶msatIndex:2];

        [invocations etSelector:action];

        [invocation setTarget:target];

        [invocation invoke];

        return nil;

    }

...

    return [target performSelector:action withObject:params];

}

CTMediator+HandyTools 增加CTMediator的功能

模块分类 请求者

CTMediator+CTMediatorModuleAActions

- (UIViewController *)CTMediator_viewControllerForDetail;

外界调用分类CTMediator_viewControllerForDetail 就可以执行详情页

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容