最近在重构一个很老的项目,项目很庞大,之前也没有看过这个项目,那叫一个头疼,永远都是牵一发而动全身,代码之间的耦合除了大还是大,#import基本每个文件都是一大堆,就连封装的控件也是有很强的耦合性,因此在重构过程中最主要的问题就是解耦和重构业务代码,去除很老旧的东西.今天就来记录一下ios组件(模块)的构建思路.
一般在项目中模块和模块之间的通信大多都是从一个页面跳到另外一个页面,大多是这样
#import "FZXAddRenovationDiaryViewController.h"
#pragma mark 跳转到 写日记
- (void)gotoAddRenovationDiary {
self.editDiaryBtn.userInteractionEnabled = NO;
FZXAddRenovationDiaryViewController *addDiaryVC = [[FZXAddRenovationDiaryViewController alloc] init];
addDiaryVC.orderId = self.orderID;
[self.navigationController pushViewController:addDiaryVC animated:YES];
}
但是这样出现的结果就是一旦工程很庞大,#import
便会变成一堆一堆,要想解决这个问题可以采用rntime动态的调用类方法,不再用#import
某个文件
- (void)gotoAddRenovationDiary:(NSString *)orderID {
Class cls = NSClassFromString(@"FZXAddRenovationDiaryViewController");
//在FZXAddRenovationDiaryViewController控制器中声明addRenovationDiaryViewController: orderID:类方法;
UIViewController *diarviewVC = [cls performSelector:NSSelectorFromString(@"addRenovationDiaryViewController":") withObject:@{@"orderID":orderID}];
[self.navigationController pushViewController:diarviewVC];
}
这样虽然不用再导入文件,但是每处调用都得写这么多,而且地方分散,因此创建一个联系的中间层,把这些东西统一写到这个文件中
//创建Mediator类,并在.h中声明一个类方法;
@interface Mediator : NSObject
+(UIViewController *)OneViewController_viewController:(NSString *)viewStr andColor:(UIColor *)color;
@end
//.m中的实现
#import "Mediator.h"
#import <objc/runtime.h>
@implementation Mediator
+(UIViewController *)OneViewController_viewController:(NSString *)viewStr andColor:(UIColor *)color{
Class cls = NSClassFromString(viewStr);
//添加安全判断,判断传过来的字符串所对应的类是否存在
if (object_isClass(cls)) {
//经测试runtime动态生成类并调用方法只能掉类方法不能调用实例方法
return [cls performSelector:NSSelectorFromString(@"initoneViewConrllerWithcolor:") withObject:@{@"color":color}];
}
return nil;
}
@end
OneViewController中的代码实现为.h
//.h
@interface OneViewController : UIViewController
+(UIViewController *)initoneViewConrllerWithcolor:(UIColor *)color;
-(UIViewController *)initWithcolor:(UIColor *)color;
@end
//.m
+(UIViewController *)initoneViewConrllerWithcolor:(UIColor *)color{
return [[self alloc]initWithcolor:color];
}
-(UIViewController *)initWithcolor:(UIColor *)color{
if (self = [super init]) {
self.color = color;
return self;
}
return nil;
}
模拟模块之间的调用,无论此页面和多少个页面有关系,都交给Meditor来处理即可
#import "Mediator.h"
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UIViewController *vc = [Mediator OneViewController_viewController:@"OneViewController" andColor:[UIColor redColor]];
if (vc != nil) {
[self presentViewController:vc animated:YES completion:^{
}];
}
}
网友评论