iOS使用核心的50行代码撸一个路由组件

2020-01-21 07:11:07于丽
  • 获取到路径对应的节点,path会使用"/"符拆分为多个pathItem,每个pathItem都会保存在一个Dictionary对应的位置上,subRouterMapWithPath负责深度遍历Dictionary,然后找到对应的位置
  • 把YTRouterActionObject对象保存在上一步找到的位置中

    以上步骤对应的代码如下:

    
    - (void)registerPath:(NSString *)path actionBlock:(RouterActionBlock)actionBlock {
     YTRouterActionObject *actionObject = [YTRouterActionObject new];
     actionObject.path = path;
     actionObject.actionBlock = actionBlock;
     NSMutableDictionary *subRouter = [self subRouterMapWithPath:path];
     subRouter[YTRouterActionObjectKey] = actionObject;
    }
    - (NSMutableDictionary *)subRouterMapWithPath:(NSString *)path {
     NSArray *components = [path componentsSeparatedByString:@"/"];
     NSMutableDictionary *subRouter = self.routerMap;
     for (NSString *component in components) {
      if (component.length == 0) {
       continue;
      }
      if (!subRouter[component]) {
       subRouter[component] = [NSMutableDictionary new];
      }
      subRouter = subRouter[component];
     }
     return subRouter;
    }

    在Demo中注册的几个路由最终的配置如下,比如home/messagelist对应的路由配置保存在<YTRouterActionObject: 0x6040000365e0>对象中

    
    Printing description of self->_routerMap:
    {
     home =  {
      "_" = "<YTRouterActionObject: 0x60c00003b040>";
      messagelist =   {
       "_" = "<YTRouterActionObject: 0x6040000365e0>";
       detail =    {
        "_" = "<YTRouterActionObject: 0x600000038ec0>";
       };
       getmessage =    {
        "_" = "<YTRouterActionObject: 0x600000038e80>";
       };
      };
     };
    }

    路由使用实现

    路由使用实现时序图:

    iOS,代码,路由组件