MGJRouter源码解析
MGJRouter是实现iOS组件间交互的工具之一,路由的使用降低了不同模块之间的耦合度,提高代码的复用率以及不同模块间重组的灵活度,下面我就针对MGJRouter说一下自己的理解:
注册
routes主要用于存储已经注册过的路径及block
@property (nonatomic) NSMutableDictionary *routes;
下面三个方法是注册时对URL进行递归遍历以及对block进行存储
- (void)addURLPattern:(NSString *)URLPattern andHandler:(MGJRouterHandler)handler { //解析当前 URL 并转化出字典存贮在self.routes中 NSMutableDictionary *subRoutes = [self addURLPattern:URLPattern]; //将block存入到字典中 if (handler && subRoutes) { subRoutes[@"_"] = [handler copy]; } } - (void)addURLPattern:(NSString *)URLPattern andObjectHandler:(MGJRouterObjectHandler)handler { NSMutableDictionary *subRoutes = [self addURLPattern:URLPattern]; if (handler && subRoutes) { subRoutes[@"_"] = [handler copy]; } } - (NSMutableDictionary *)addURLPattern:(NSString *)URLPattern { //拆分当前URL NSArray *pathComponents = [self pathComponentsFromURL:URLPattern]; NSMutableDictionary* subRoutes = self.routes; //进行轮循依次将component按照字典存入 for (NSString* pathComponent in pathComponents) { //由于按照顺序存储所以先存入的生效,后面的将无法存入 if (![subRoutes objectForKey:pathComponent]) { //依次生成字典存入上一层字典 subRoutes[pathComponent] = [[NSMutableDictionary alloc] init]; } //依次将最里面的字典赋值给subRoutes subRoutes = subRoutes[pathComponent]; } //将最里层的字典返回 return subRoutes; }
最终存储数据的格式如下,调用时会对其中的字典进行递归查找
{ LWT = { Home = { OtherViewController = { "_" = "<__NSGlobalBlock__: 0x10c5b0168>"; }; SecondViewController = { "_" = "<__NSGlobalBlock__: 0x10c5b0148>"; }; }; }; }
调用
调用时会将路径进行分解递归查找到对应的block,并将传递进来的参数进行存储
+ (void)openURL:(NSString *)URL { [self openURL:URL completion:nil]; } + (void)openURL:(NSString *)URL completion:(void (^)(id result))completion { [self openURL:URL withUserInfo:nil completion:completion]; } + (void)openURL:(NSString *)URL withUserInfo:(NSDictionary *)userInfo completion:(void (^)(id result))completion { URL = [URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSMutableDictionary *parameters = [[self sharedInstance] extractParametersFromURL:URL matchExactly:NO]; //遍历字典 [parameters enumerateKeysAndObjectsUsingBlock:^(id key, NSString *obj, BOOL *stop) { if ([obj isKindOfClass:[NSString class]]) { //读出 parameters[key] = [obj stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; } }]; if (parameters) { //取出block并根据请求进行回调 MGJRouterHandler handler = parameters[@"block"]; //将方法中的参数和block保存下来以便后期使用 if (completion) { parameters[MGJRouterParameterCompletion] = completion; } if (userInfo) { parameters[MGJRouterParameterUserInfo] = userInfo; } if (handler) { //删除注册时的block并发起回调 [parameters removeObjectForKey:@"block"]; NSLog(@"开始调用Block"); handler(parameters); } } }
路由注销
- (void)removeURLPattern:(NSString *)URLPattern { //URL分解 NSMutableArray *pathComponents = [NSMutableArray arrayWithArray:[self pathComponentsFromURL:URLPattern]]; // 只删除该 pattern 的最后一级 if (pathComponents.count >= 1) { // 假如 URLPattern 为 a/b/c, components 就是 @"a.b.c" 正好可以作为 KVC 的 key //获取数组拼接的key NSString *components = [pathComponents componentsJoinedByString:@"."]; NSMutableDictionary *route = [self.routes valueForKeyPath:components]; if (route.count >= 1) { //删除最后一个参数 NSString *lastComponent = [pathComponents lastObject]; [pathComponents removeLastObject]; // 有可能是根 key,这样就是 self.routes 了 route = self.routes; //获取字典层级的倒数第二层字典并删除 if (pathComponents.count) { NSString *componentsWithoutLast = [pathComponents componentsJoinedByString:@"."]; route = [self.routes valueForKeyPath:componentsWithoutLast]; } [route removeObjectForKey:lastComponent]; } } }
路由判断
即根据路径获取相应的block,如果没有查找到则返回nil
//根据路径取出block - (NSMutableDictionary *)extractParametersFromURL:(NSString *)url matchExactly:(BOOL)exactly { NSMutableDictionary* parameters = [NSMutableDictionary dictionary]; parameters[MGJRouterParameterURL] = url; //获取路由中存储的路由集合 NSMutableDictionary* subRoutes = self.routes; //传入地址的组件 NSArray* pathComponents = [self pathComponentsFromURL:url]; BOOL found = NO; // borrowed from HHRouter(https://github.com/Huohua/HHRouter) //遍历传入URL组件 for (NSString* pathComponent in pathComponents) { // 对 key 进行排序,这样可以把 ~ 放到最后 NSArray *subRoutesKeys =[subRoutes.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) { return [obj1 compare:obj2]; }]; //遍历全部路由key值进行比对查找 for (NSString* key in subRoutesKeys) { if ([key isEqualToString:pathComponent] || [key isEqualToString:MGJ_ROUTER_WILDCARD_CHARACTER]) { found = YES; //查找到后取出子字典继续遍历 subRoutes = subRoutes[key]; break; } else if ([key hasPrefix:@":"]) { //判断字符串是否以:为前缀 found = YES; subRoutes = subRoutes[key]; NSString *newKey = [key substringFromIndex:1]; NSString *newPathComponent = pathComponent; // 再做一下特殊处理,比如 :id.html -> :id if ([self.class checkIfContainsSpecialCharacter:key]) { NSCharacterSet *specialCharacterSet = [NSCharacterSet characterSetWithCharactersInString:specialCharacters]; NSRange range = [key rangeOfCharacterFromSet:specialCharacterSet]; if (range.location != NSNotFound) { // 把 pathComponent 后面的部分也去掉 newKey = [newKey substringToIndex:range.location - 1]; NSString *suffixToStrip = [key substringFromIndex:range.location]; newPathComponent = [newPathComponent stringByReplacingOccurrencesOfString:suffixToStrip withString:@""]; } } parameters[newKey] = newPathComponent; break; } else if (exactly) { found = NO; } } // 如果没有找到该 pathComponent 对应的 handler,则以上一层的 handler 作为 fallback if (!found && !subRoutes[@"_"]) { return nil; } } // Extract Params From Query. NSArray<NSURLQueryItem *> *queryItems = [[NSURLComponents alloc] initWithURL:[[NSURL alloc] initWithString:url] resolvingAgainstBaseURL:false].queryItems; for (NSURLQueryItem *item in queryItems) { parameters[item.name] = item.value; } //将block放入字典中返回 if (subRoutes[@"_"]) { parameters[@"block"] = [subRoutes[@"_"] copy]; } return parameters; }
MGJRouter的使用
- 注册
//无参数的 [MGJRouter registerURLPattern:[self appendAnimUrl:@"SecondViewController"] toHandler:^(NSDictionary *routerParameters) { NSLog(@"routerParameters[ViewController]:%@", routerParameters[@"ViewController"]); // halfrost UINavigationController *navigationVC = routerParameters[MGJRouterParameterUserInfo][@"navigationVC"]; SecondController *vc = [[SecondController alloc] init]; [navigationVC pushViewController:vc animated:YES]; }]; //有参数无回调 [MGJRouter registerURLPattern:[self appendAnimUrl:@"OtherViewController"] toHandler:^(NSDictionary *routerParameters) { UINavigationController *navigationVC = routerParameters[MGJRouterParameterUserInfo][@"navigationVC"]; NSString *labelText = routerParameters[MGJRouterParameterUserInfo][@"text"]; OtherViewController *vc = [[OtherViewController alloc] init]; vc.titleText = labelText; [navigationVC pushViewController:vc animated:YES]; }]; //有参数有回调 [MGJRouter registerURLPattern:[self appendAnimUrl:@"ThridViewController"] toHandler:^(NSDictionary *routerParameters) { UINavigationController *navigationVC = routerParameters[MGJRouterParameterUserInfo][@"navigationVC"]; void(^block)(NSString *) = routerParameters[MGJRouterParameterUserInfo][@"block"]; ThridViewController *vc = [[ThridViewController alloc] init]; vc.titleText = routerParameters[MGJRouterParameterUserInfo][@"text"]; vc.backBlock = block; [navigationVC pushViewController:vc animated:YES]; }];
- 调用
由于是通过路径进行的查找相应的controller增加了大量的硬编码,直接通过MGJrouter的方法调用无疑会增加pushController中代码的复杂度,同时也提高了开发者之间沟通交流的成本,在这里通过对MGJrouter进行分类增加跳转方法以便降低模块间沟通的成本,同理注册的时候也可以对其增加分类以防止单个文件过重,并且在此处可以增加参数判断以防止传参丢失等情况的出现
#define Home_base_Url @"LWT://Home/:name" + (void)pushSecondCtl:(UINavigationController *)nav { [MGJRouter openURL:[MGJRouter generateURLWithPattern:Home_base_Url parameters:@[@"SecondViewController"]] withUserInfo:@{@"navigationVC":nav} completion:nil]; } + (void)pushOtherController:(UINavigationController *)nav title:(NSString *)titleText { [MGJRouter openURL:[MGJRouter generateURLWithPattern:Home_base_Url parameters:@[@"OtherViewController"]] withUserInfo:@{@"navigationVC" : nav, @"text": titleText, } completion:nil]; } + (void)pushThridController:(UINavigationController *)nav title:(NSString *)titleText block:(void (^)(NSString * result))block { [MGJRouter openURL:[MGJRouter generateURLWithPattern:Home_base_Url parameters:@[@"ThridViewController"]] withUserInfo:@{@"navigationVC" : nav, @"text": titleText, @"block":block } completion:nil]; }
以上就是我对MGJrouter的理解及使用,如有不足欢迎补充