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的理解及使用,如有不足歡迎補充