1.注册URL,HHRoute中的“route”是没有schem的,他的造型有两种:
1."user/name/"
url | 匹配结果 | |
---|---|---|
"/user/name/xiaoming" | 不匹配 | |
"/user" | 不匹配 | |
"/user/name" | 匹配 |
只有和1一毛一样的才匹配成功
2."user/:name"
url | result | |
---|---|---|
"/user" | 匹配 | |
"user/xiaoming/" | 匹配 | |
"/user/name/xiaoming" | 不匹配 |
同时传个目标控制器一个params{“name”:“xiaoming”},只要目标控制器实现一个setParams方法即可取出其中参数赋值
-(void)map:(NSString *)route toControllerClass:(Class)controllerClass;
注册一个路径地址和controller对应
-(void)map:(NSString *)route toBlock:(HHRouterBlock)block;
注册一个路径地址和block回调对应
使用详解:
1.[[HHRouter shared] map:@"/user/:userId/"
toControllerClass:[UserViewController class]];
2.[[HHRouter shared] map:@"/user/:userId/story/"
toControllerClass:[StoryListViewController class]];
3. [[HHRouter shared] map:@"/story/:storyId/"
toControllerClass:[StoryViewController class]];
[HHRouter shared]的单例中一个routes属性的字典中维护了全局的url到controller或者block对应关系
根据route返回一个嵌套的字典,键是pathCompanent,值是字典,字典的键是下一个pathCompanent,最后一个字典的键是"_",值是对应的controller或者block变量
调用1方法后routes里的保存情况
{"user":
{":userId":
{
"_":[UserViewController class]
}
}
}
调用2方法后routes里的保存情况
{"user":
{":userId":
{
"_":[UserViewController class]
"story":
{
"_":[StoryListViewController class]
}
}
}
}
调用3方法后routes里的保存情况
{
"user":
{":userId":
{
"_":[UserViewController class]
"story":
{
"_":[StoryListViewController class]
}
}
}
"story":
{
" :storyId":
{
"_":[StoryViewController class]
}
}
}
2.返回对应的controller和block
-(UIViewController *)matchController:(NSString *)route;
-(HHRouterBlock)matchBlock:(NSString *)route;
-
route和url匹配逻辑
1. route中如果以":"开头,将url中对应的pathComponent塞进params字典中作为传参,校验结果返回"YES"(found = YES),另外url中"?a=1&b=2"也会塞进params中
2. 不以":"开头,只有url中对应的pathComponent与route中对应的pathComponent一致时,校验结果才返回"YES"(found = YES)
for (NSString *key in subRoutesKeys) {
if ([subRoutesKeys containsObject:pathComponent]) {
found = YES;
subRoutes = subRoutes[pathComponent];
break;
} else if ([key hasPrefix:@":"]) {
found = YES;
subRoutes = subRoutes[key];
params[[key substringFromIndex:1]] = pathComponent;
break;
}
}
-
params赋值
-
controller实现
- (void)setParams:(NSDictionary *)paramsDictionary
方法 -
block直接调用
-
-(id)callBlock:(NSString *)route
{
NSDictionary *params = [self paramsInRoute:route];
HHRouterBlock routerBlock = [params[@"block"] copy];
if (routerBlock) {
return routerBlock([params copy]);
}
return nil;
}