美文网首页
Class-Protocol Router

Class-Protocol Router

作者: 桔子听 | 来源:发表于2019-05-09 11:20 被阅读0次

    定义一个protocol,叫protocolB,让BViewController实现。

    protocolB里面可以定义BViewController创建时需要的参数,例如这里的nameage

    @protocol ProtocolB <NSObject>
    - (void)setBViewControllerName:(NSString *)name age:(int)age;
    @end
    

    BViewController实现protocolB

    #import "ProtocolB.h"
    
    - (void)setBViewControllerName:(NSString *)name age:(int)age
    {
        self.nameText = name;
        self.ageText = [NSString stringWithFormat:@"%d",age];
    }
    

    router#import "ProtocolB.h",定义register方法,将protocol和class对应起来,保存到字典protocol_class_map

    @property(nonatomic, strong) NSMutableDictionary *protocol_class_map;
    - (void)registerProtocol:(Protocol *)protocol forClass:(Class)cls;
    

    BViewController里注册

    // 如果在其他地方注册,必然要引入BViewController,造成耦合
    [[Router shared] registerProtocol:@protocol(ProtocolB) forClass:BViewController.class];
    

    register方法里将BViewControllerProtocolB关联,

    AViewController

    #import "Router.h"
    #import "ProtocolB.h"
    
    [Router.shared push:@protocol(ProtocolB) param:@{@"name":@"zhangsan",@"age":@(18)}];
    

    push方法实现

    - (void)push:(Protocol *)protocol param:(NSDictionary *)param
    {
        
        Class cls = self.protocol_class_map[NSStringFromProtocol(protocol)];
        UIViewController<ProtocolB> *bViewController = [[cls alloc] init];
        [bViewController setBViewControllerName:param[@"name"] age:[param[@"age"] intValue]];
        
        [[self topViewController] pushViewController:bViewController animated:YES];
    }
    

    这段代码干的事:

    1.通过协议ProtocolB,找到对应的BViewController类,创建实例

    Class cls = self.protocol_class_map[NSStringFromProtocol(protocol)];
    UIViewController<ProtocolB> *bViewController = [[cls alloc] init];
    

    2.因为实现了协议,可以通过协议传入参数

    [bViewController setBViewControllerName:param[@"name"] age:[param[@"age"] intValue]];
    

    用一张图总结:

    Class_Protocol_Router.png

    再总结:

    我觉得最理想的router是,只要AViewController引入router就可以跳转到BViewController

    这里的操作是,ViewController要有相应的protocol,然后ViewController要实现这个protocol,然后ViewController要注册protocolViewController的关联,因为要router来注册,所以还要导入router

    这里的router还要导入protocol

    router通过导入每个ViewController对应的Protocol来避免导入具体的ViewController,本质上,我觉得没有区别。

    的确比较麻烦,不是很好的方案。

    demo Class_Protocol_Router

    相关文章

      网友评论

          本文标题:Class-Protocol Router

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