分析Router中的Protocol方式和Category方式的優缺點

在Casa發佈CTMeditor後,咱們都知道router能夠用targert-action的方式直接調起你須要的controller來作router。git

可是這種形式存在的問題你們基本都提出了:就是硬編碼問題,在編寫Category的時候你不可避免的須要以硬編碼的方式去寫target和action以及參數轉換。後來再此基礎上,有人就結合蘑菇街的protocol形式來作,就是要拋出的東西,我以protocol的形式給出去,這樣的話你就很清楚的知道你要調用什麼,不須要中間硬編碼的過程。github

這是protocol形式解決的核心問題。惟一的不一樣,在於protocol須要依賴於業務自己。在硬編碼和這個依賴之間的取捨,我看來硬編碼問題仍是要嚴重些的,因此推薦protocl結合CTMeditor的形式來作router可能更合適些。web

和蘑菇街的老的url註冊形式應該是不須要比較了,這個須要每一個去註冊url,管理url,成本過高。並且註冊聽說還有crash風險,雖然我沒遇到過。bash

Category:

#pragma mark - category的形式
- (void)webBlock {
    UIViewController *controller = [[KZWRouter sharedRouter] kzw_KZWWebViewController:@"https%3a%2f%2fwww.zhihu.com%2f" callBackHandle:^(NSString *result) {
        NSLog(@"result:%@", result);
    }];
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:controller] animated:YES completion:nil];
}
複製代碼

Protocol:

#pragma mark - protocol的形式
- (void)webAction {
    id<KZWWebView> KZWWebViewService = [[KZWRouter sharedRouter] findProtocolService:@protocol(KZWWebView)];
    UIViewController *controller = [KZWWebViewService kzw_KZWWebViewController:@"https%3a%2f%2fwww.zhihu.com%2f" callBackHandle:^(NSString *result) {
        NSLog(@"result:%@", result);
    }];
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:controller] animated:YES completion:nil];
}
複製代碼

以上三種方式我都在本身的github中開源。編碼

代碼地址: Protocol和Category URL形式url

相關文章
相關標籤/搜索