美文网首页解耦
IOS页面组件化、解耦(CTMediator)

IOS页面组件化、解耦(CTMediator)

作者: 海牛骑士 | 来源:发表于2018-12-07 17:44 被阅读50次

    日常开发中我们经常遇到不同模块之间需要进行页面的跳转。我们常规的做法就是import 我们需要跳转页面的头文件 然后实例化进行跳转。如果同一个页面需要使用多次 我们就得重复多次这样的操作。模块之间 这样的多了之后 就会造成页面高度耦合管理混乱。

    通过casa的iOS应用架构谈 组件化方案 了解了CTMmediator 这个组件化工具

    下面就用CTMmediator工具 实现没有添加依赖关系的情况下实现页面的跳转。

    源码 CTMmediator.h 有几个方法 实例化 远程APP调用入口 本地组件入口 释放缓存

    #import <UIKit/UIKit.h>
    
    extern NSString * const kCTMediatorParamsKeySwiftTargetModuleName;
    
    @interface CTMediator : NSObject
    
    + (instancetype)sharedInstance;
    
    // 远程App调用入口
    - (id)performActionWithUrl:(NSURL *)url completion:(void(^)(NSDictionary *info))completion;
    // 本地组件调用入口
    - (id)performTarget:(NSString *)targetName action:(NSString *)actionName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget;
    - (void)releaseCachedTargetWithTargetName:(NSString *)targetName;
    
    @end
    

    CTMmediator.m

    
    #import "CTMediator.h"
    #import <objc/runtime.h>
    
    NSString * const kCTMediatorParamsKeySwiftTargetModuleName = @"kCTMediatorParamsKeySwiftTargetModuleName";
    
    @interface CTMediator ()
    
    @property (nonatomic, strong) NSMutableDictionary *cachedTarget;
    
    @end
    
    @implementation CTMediator
    
    #pragma mark - public methods
    + (instancetype)sharedInstance
    {
        static CTMediator *mediator;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            mediator = [[CTMediator alloc] init];
        });
        return mediator;
    }
    
    /*
     scheme://[target]/[action]?[params]
     
     url sample:
     aaa://targetA/actionB?id=1234
     */
    
    - (id)performActionWithUrl:(NSURL *)url completion:(void (^)(NSDictionary *))completion
    {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        NSString *urlString = [url query];
        for (NSString *param in [urlString componentsSeparatedByString:@"&"])
        {
            NSArray *elts = [param componentsSeparatedByString:@"="];
            if([elts count] < 2) continue;
            [params setObject:[elts lastObject] forKey:[elts firstObject]];
        }
        
        // 这里这么写主要是出于安全考虑,防止黑客通过远程方式调用本地模块。这里的做法足以应对绝大多数场景,如果要求更加严苛,也可以做更加复杂的安全逻辑。
        NSString *actionName = [url.path stringByReplacingOccurrencesOfString:@"/" withString:@""];
        if ([actionName hasPrefix:@"native"]) {
            return @(NO);
        }
        
        // 这个demo针对URL的路由处理非常简单,就只是取对应的target名字和method名字,但这已经足以应对绝大部份需求。如果需要拓展,可以在这个方法调用之前加入完整的路由逻辑
        id result = [self performTarget:url.host action:actionName params:params shouldCacheTarget:NO];
        if (completion) {
            if (result) {
                completion(@{@"result":result});
            } else {
                completion(nil);
            }
        }
        return result;
    }
    
    - (id)performTarget:(NSString *)targetName action:(NSString *)actionName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget
    {
        NSString *swiftModuleName = params[kCTMediatorParamsKeySwiftTargetModuleName];
        
        // generate target
        NSString *targetClassString = nil;
        if (swiftModuleName.length > 0) {
            targetClassString = [NSString stringWithFormat:@"%@.Target_%@", swiftModuleName, targetName];
        } else {
            targetClassString = [NSString stringWithFormat:@"Target_%@", targetName];
        }
        NSObject *target = self.cachedTarget[targetClassString];
        if (target == nil) {
            Class targetClass = NSClassFromString(targetClassString);
            target = [[targetClass alloc] init];
        }
        
        // generate action
        NSString *actionString = [NSString stringWithFormat:@"Action_%@:", actionName];
        SEL action = NSSelectorFromString(actionString);
        
        if (target == nil) {
            // 这里是处理无响应请求的地方之一,这个demo做得比较简单,如果没有可以响应的target,就直接return了。实际开发过程中是可以事先给一个固定的target专门用于在这个时候顶上,然后处理这种请求的
            [self NoTargetActionResponseWithTargetString:targetClassString selectorString:actionString originParams:params];
            return nil;
        }
        
        if (shouldCacheTarget) {
            self.cachedTarget[targetClassString] = target;
        }
    
        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];
                [self.cachedTarget removeObjectForKey:targetClassString];
                return nil;
            }
        }
    }
    
    - (void)releaseCachedTargetWithTargetName:(NSString *)targetName
    {
        NSString *targetClassString = [NSString stringWithFormat:@"Target_%@", targetName];
        [self.cachedTarget removeObjectForKey:targetClassString];
    }
    
    #pragma mark - private methods
    - (void)NoTargetActionResponseWithTargetString:(NSString *)targetString selectorString:(NSString *)selectorString originParams:(NSDictionary *)originParams
    {
        SEL action = NSSelectorFromString(@"Action_response:");
        NSObject *target = [[NSClassFromString(@"Target_NoTargetAction") alloc] init];
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        params[@"originParams"] = originParams;
        params[@"targetString"] = targetString;
        params[@"selectorString"] = selectorString;
        
        [self safePerformAction:action target:target params:params];
    }
    
    - (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];
    
        if (strcmp(retType, @encode(void)) == 0) {
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
            [invocation setArgument:&params atIndex:2];
            [invocation setSelector:action];
            [invocation setTarget:target];
            [invocation invoke];
            return nil;
        }
    
        if (strcmp(retType, @encode(NSInteger)) == 0) {
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
            [invocation setArgument:&params atIndex:2];
            [invocation setSelector:action];
            [invocation setTarget:target];
            [invocation invoke];
            NSInteger result = 0;
            [invocation getReturnValue:&result];
            return @(result);
        }
    
        if (strcmp(retType, @encode(BOOL)) == 0) {
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
            [invocation setArgument:&params atIndex:2];
            [invocation setSelector:action];
            [invocation setTarget:target];
            [invocation invoke];
            BOOL result = 0;
            [invocation getReturnValue:&result];
            return @(result);
        }
    
        if (strcmp(retType, @encode(CGFloat)) == 0) {
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
            [invocation setArgument:&params atIndex:2];
            [invocation setSelector:action];
            [invocation setTarget:target];
            [invocation invoke];
            CGFloat result = 0;
            [invocation getReturnValue:&result];
            return @(result);
        }
    
        if (strcmp(retType, @encode(NSUInteger)) == 0) {
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
            [invocation setArgument:&params 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
    }
    
    #pragma mark - getters and setters
    - (NSMutableDictionary *)cachedTarget
    {
        if (_cachedTarget == nil) {
            _cachedTarget = [[NSMutableDictionary alloc] init];
        }
        return _cachedTarget;
    }
    

    根据本地化组件接口进行跳转也非常的简单 创建一个Target_page 类 抛出我们的控制器

    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    
    @interface Target_page : NSObject
    //项目组件接口
    -(UIViewController *)Action_TagetViewController:(NSDictionary *)params;
    
    @end
    #import "Target_page.h"
    #import <UIKit/UIKit.h>
    #import "TagetViewController.h"
    @implementation Target_page
    -(UIViewController *)Action_TagetViewController:(NSDictionary *)params
    {
        
        TagetViewController * view = [[TagetViewController alloc]init];
        //根据需求是否进行数据传递
        
        return  view;
        
    }
    @end
    

    创建一个CTMmediator分类 CTMediator+NewsActions 这里面就是通过我们的中间层CTMmediator 去获取我们的控制器

    #import "CTMediator.h"
    #import <UIKit/UIKit.h>
    
    @interface CTMediator (NewsActions)
    
    -(UIViewController *)show_TagetViewControllerDetails:(NSDictionary *)dict;
    
    
    @end
    
    
    #import "CTMediator+NewsActions.h"
    
    
    NSString * const kCTMediatorTargetnews = @"page";
    
    NSString * const kCTMediatorActionTagetViewController = @"TagetViewController";
    
    @implementation CTMediator (NewsActions)
    
    -(UIViewController *)Action_TagetViewController:(NSDictionary *)dict
    {
        UIViewController  * viewController =  [self performTarget:kCTMediatorTargetnews action:kCTMediatorActionTagetViewController params:@{@"key":@"value"} shouldCacheTarget:NO];
        
        if ([viewController isKindOfClass:[UIViewController class]])
        {
            return viewController;
        }
        else
        {
            
             //carsh 处理
            return  nil;
        }
       
    }
    @end
    

    获取对象 实现跳转 这样页面间没有import 没有管理实现了跳转达到了页面解藕的目的

         UIViewController   * controller =  [[CTMediator sharedInstance] show_TagetViewControllerDetails:nil];
          [self.navigationController pushViewController:controller animated:YES];
    
    

    在上面实现的过程中 主要调用了 - (id)performTarget:(NSString *)targetName action:(NSString *)actionName params:(NSDictionary *)params shouldCacheTarget:(BOOL)shouldCacheTarget

    注意需要传递几个参数

    • taegetName 抛出对象类的名称 只需要传递Target_后面的部分

    • actionName 控制器名称

    • params 跳转需要的参数

    • shouldCacheTarget 是否缓存 方便经常使用

    点进实现查看 主要是通过runtime 消息转发 动态解析去实现

    首先通过runtime NSClassFromString()去找到我们抛出的类 Target_xxxx;

    
       NSString *swiftModuleName = params[kCTMediatorParamsKeySwiftTargetModuleName];
        
        // generate target
        NSString *targetClassString = nil;
        if (swiftModuleName.length > 0) {
            targetClassString = [NSString stringWithFormat:@"%@.Target_%@", swiftModuleName, targetName];
        } else {
            targetClassString = [NSString stringWithFormat:@"Target_%@", targetName];
        }
        NSObject *target = self.cachedTarget[targetClassString];
        if (target == nil) {
            Class targetClass = NSClassFromString(targetClassString);
            target = [[targetClass alloc] init];
        }
    

    通过 runtime NSSelectorFromString()去找到我们类里面的实现方法

       NSString *actionString = [NSString stringWithFormat:@"Action_%@:", actionName];
        SEL action = NSSelectorFromString(actionString);
    

    然后通过消息转发去响应 并返回我们创建的实例

    - (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];
    
        if (strcmp(retType, @encode(void)) == 0) {
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
            [invocation setArgument:&params atIndex:2];
            [invocation setSelector:action];
            [invocation setTarget:target];
            [invocation invoke];
            return nil;
        }
    
        if (strcmp(retType, @encode(NSInteger)) == 0) {
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSig];
            [invocation setArgument:&params atIndex:2];
            [invocation setSelector:action];
            [invocation setTarget:target];
            [invocation invoke];
            NSInteger result = 0;
            [invocation getReturnValue:&result];
            return @(result);
        }
    

    相关文章

      网友评论

        本文标题:IOS页面组件化、解耦(CTMediator)

        本文链接:https://www.haomeiwen.com/subject/hpjthqtx.html