【源碼閱讀】JLRoutes

介紹

JLRoutes是一個URL解析庫,可以很方便的處理不同URL schemes以及解析它們的參數(shù),并通過回調(diào)block來處理URL對應(yīng)的操作。

使用場景

對一個App中單獨的模塊,可以使用openURL的方式進行頁面跳轉(zhuǎn),很好地解耦不同的模塊铃绒,蘑菇街的組件化之路就是基于URL跳轉(zhuǎn)的方式,當然casa也提出了Target—Action模式下配合category實現(xiàn)的組件化架構(gòu)螺捐,時隔幾個月又重寫看了兩位大神的文章匿垄,感覺腦細胞真的不夠用啊。

我沒有組件化的經(jīng)驗归粉,所以使用JSRoutes僅限于遠程調(diào)用(服務(wù)端下發(fā)椿疗、Push跳轉(zhuǎn)等),本地調(diào)用還是不太敢用這種URL的統(tǒng)一跳轉(zhuǎn)糠悼。

使用實例

先來個簡單的使用demo

在didFinishLaunchingWithOptions中注冊所有的URL

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [JLRoutes addRoute:@"/:controller" handler:^BOOL(NSDictionary *parameters) {
        NSString *controller = parameters[@"controller"];
        
        [self.window.rootViewController presentViewController:[[NSClassFromString(controller) alloc] init] animated:YES completion:^{
            
        }];
        return YES;
    }];
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
  return [JLRoutes routeURL:url];
}

打開指定URL資源

NSURL *viewUserURL = [NSURL URLWithString:@"myapp://user/view/joeldev"];
[[UIApplication sharedApplication] openURL:viewUserURL];

原理

JLRoutes本質(zhì)可以理解為:保存一個全局的Map届榄,key是url,value是對應(yīng)的block倔喂,url和block都會常駐在內(nèi)存中铝条,這也是為什么casa反對使用URL跳轉(zhuǎn)來實現(xiàn)組件化的原因,當注冊的url很多了席噩,對內(nèi)存的消耗也是很大的班缰。當打開一個URL時,JLRoutes就可以遍歷這個全局的map悼枢,通過url來執(zhí)行對應(yīng)的block埠忘。

內(nèi)部實現(xiàn)

namespace

routeControllersMap是一個NSDictionary類型的單例,key是namespace,value是一個array莹妒,里面包含當前namespace下所有的routes名船。

命名空間也對應(yīng)我們的URL scheme。

globalRoutes返回全局命名空間

+ (instancetype)globalRoutes {
    return [self routesForScheme:kJLRoutesGlobalNamespaceKey];
}

routesForScheme返回指定scheme對應(yīng)的命名空間旨怠,如果不存在就創(chuàng)建一個


+ (instancetype)routesForScheme:(NSString *)scheme {
    JLRoutes *routesController = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        routeControllersMap = [[NSMutableDictionary alloc] init];
    });
    
    if (!routeControllersMap[scheme]) {
        routesController = [[self alloc] init];
        routesController.namespaceKey = scheme;
        routeControllersMap[scheme] = routesController;
    }
    
    routesController = routeControllersMap[scheme];
    
    return routesController;
}
添加Route

注冊一個Route到global scheme namespace渠驼,并設(shè)置其優(yōu)先級(默認優(yōu)先級是0),block返回一個bool鉴腻,如果返回YES表示當前匹配成功迷扇,如果返回NO表示繼續(xù)匹配其他Route(_JLRoute對象)

一個內(nèi)部類,用下劃線開頭命名_JLRoute,其結(jié)構(gòu)如下:

@interface _JLRoute : NSObject

@property (nonatomic, weak) JLRoutes *parentRoutesController;
@property (nonatomic, strong) NSString *pattern;
@property (nonatomic, strong) BOOL (^block)(NSDictionary *parameters);
@property (nonatomic, assign) NSUInteger priority;
@property (nonatomic, strong) NSArray *patternPathComponents;

- (NSDictionary *)parametersForURL:(NSURL *)URL components:(NSArray *)URLComponents;

@end

addRoute這個方法對原始routePattern字符串做一個加工和過濾的操作爽哎,如去掉圓括號

- (void)addRoute:(NSString *)routePattern priority:(NSUInteger)priority handler:(BOOL (^)(NSDictionary *parameters))handlerBlock {
    
    // if there's a pair of parenthesis, process optionals, trim the parenthesis, put it on trimmedRoute
    NSString *trimmedRoute = routePattern;
    
    // repeat until no parenthesis pair is found
    while ([trimmedRoute rangeOfString:@")" options:NSBackwardsSearch].location > [trimmedRoute rangeOfString:@"(" options:NSBackwardsSearch].location) {
        
        //Build route with the optionals
        NSString *patternWithOptionals = [trimmedRoute stringByReplacingOccurrencesOfString:@"(" withString:@""];
        patternWithOptionals = [patternWithOptionals stringByReplacingOccurrencesOfString:@")" withString:@""];
        [self registerRoute:patternWithOptionals priority:priority handler:handlerBlock];
        
        //Build route without optionals
        NSRange rangeOfLastParentheses = [trimmedRoute rangeOfString:@"(" options:NSBackwardsSearch];
        NSRange rangeToRemove = NSMakeRange(rangeOfLastParentheses.location, trimmedRoute.length - rangeOfLastParentheses.location);
        NSString *patternWithLastOptionalRemoved = [trimmedRoute stringByReplacingCharactersInRange:rangeToRemove withString:@""];
        //Remove any parenthesis for other optionals that might still be in the route
        NSString *patternWithoutOptionals = [patternWithLastOptionalRemoved stringByReplacingOccurrencesOfString:@"(" withString:@""];
        patternWithoutOptionals = [patternWithoutOptionals stringByReplacingOccurrencesOfString:@")" withString:@""];
        [self registerRoute:patternWithoutOptionals priority:priority handler:handlerBlock];
        
        trimmedRoute = patternWithLastOptionalRemoved;
    }
    
    //Only register original route if trimmedRoute haven't been modified.
    if (trimmedRoute == routePattern) {
        [self registerRoute:routePattern priority:priority handler:handlerBlock];
    }
}

registerRoute這個方法就是把_JLRoute插入到routeControllersMap[kJLRoutesGlobalNamespaceKey]這個list中的時候蜓席,用到了插入排序的思想,priority高的在前面倦青。這樣enum這個_JLRoute List的時候,如果match pattern盹舞,就return产镐,自然就解決了「路徑匹配優(yōu)先級」的問題。

- (void)registerRoute:(NSString *)routePattern priority:(NSUInteger)priority handler:(BOOL (^)(NSDictionary *parameters))handlerBlock {
    _JLRoute *route = [[_JLRoute alloc] init];
    route.pattern = routePattern;
    route.priority = priority;
    route.block = [handlerBlock copy];
    route.parentRoutesController = self;
    
    if (!route.block) {
        route.block = [^BOOL (NSDictionary *params) {
            return YES;
        } copy];
    }
    
    if (priority == 0 || self.routes.count == 0) {
        [self.routes addObject:route];
    } else {
        NSArray *existingRoutes = self.routes;
        NSUInteger index = 0;
        BOOL addedRoute = NO;
        
        // search through existing routes looking for a lower priority route than this one
        // 找到一個優(yōu)先級低的踢步,采用插入排序
        for (_JLRoute *existingRoute in existingRoutes) {
            if (existingRoute.priority < priority) {
                // if found, add the route after it
                [self.routes insertObject:route atIndex:index];
                addedRoute = YES;
                break;
            }
            index++;
        }
        
        // if we weren't able to find a lower priority route, this is the new lowest priority route (or same priority as self.routes.lastObject) and should just be added
        if (!addedRoute)
            [self.routes addObject:route];
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末癣亚,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子获印,更是在濱河造成了極大的恐慌述雾,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件兼丰,死亡現(xiàn)場離奇詭異玻孟,居然都是意外死亡,警方通過查閱死者的電腦和手機鳍征,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門黍翎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人艳丛,你說我怎么就攤上這事匣掸。” “怎么了氮双?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵碰酝,是天一觀的道長。 經(jīng)常有香客問我戴差,道長送爸,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮碱璃,結(jié)果婚禮上弄痹,老公的妹妹穿的比我還像新娘。我一直安慰自己嵌器,他們只是感情好肛真,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著爽航,像睡著了一般蚓让。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上讥珍,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天历极,我揣著相機與錄音,去河邊找鬼衷佃。 笑死趟卸,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的氏义。 我是一名探鬼主播锄列,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼惯悠!你這毒婦竟也來了邻邮?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤克婶,失蹤者是張志新(化名)和其女友劉穎筒严,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體情萤,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡鸭蛙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了筋岛。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片规惰。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖泉蝌,靈堂內(nèi)的尸體忽然破棺而出歇万,到底是詐尸還是另有隱情,我是刑警寧澤勋陪,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布贪磺,位于F島的核電站,受9級特大地震影響诅愚,放射性物質(zhì)發(fā)生泄漏寒锚。R本人自食惡果不足惜劫映,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望刹前。 院中可真熱鬧泳赋,春花似錦、人聲如沸喇喉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽拣技。三九已至千诬,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間膏斤,已是汗流浹背徐绑。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留莫辨,地道東北人傲茄。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像沮榜,于是被迫代替她去往敵國和親盘榨。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內(nèi)容

  • 前言 隨著用戶的需求越來越多敞映,對App的用戶體驗也變的要求越來越高较曼。為了更好的應(yīng)對各種需求磷斧,開發(fā)人員從軟件工程的角...
    一縷殤流化隱半邊冰霜閱讀 87,119評論 214 1,098
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理振愿,服務(wù)發(fā)現(xiàn),斷路器弛饭,智...
    卡卡羅2017閱讀 134,651評論 18 139
  • 介紹 : JLRoutes是一個調(diào)用極少代碼 , 可以很方便的處理不同URL schemes以及解析它們的參數(shù)冕末,并...
    CoderLF閱讀 1,637評論 0 3
  • 介紹 : JLRoutes是一個調(diào)用極少代碼 , 可以很方便的處理不同URL schemes以及解析它們的參數(shù),并...
    一支煙一只猿閱讀 11,471評論 3 17
  • 文/清晨 霸凌的行為模式來自于周圍的環(huán)境 想必不少人都看了最近網(wǎng)絡(luò)上被火熱流傳的《每對母子都是生死之交侣颂,我要陪他向...
    國學媽媽閱讀 834評論 0 0