走在技术前沿的 iOS 架构实现
基于 Objective-C 實現(xiàn)的框架設(shè)計,YTKNetwork網(wǎng)絡(luò)層 + AOP替代基類 + MVVM + ReactiveObjC + JLRoutes路由
我理解的框架,就好比計算機(jī)的主板,房屋的建筑骨架,道路的基礎(chǔ)設(shè)施配套,框架搭的好,能直接影響開發(fā)者的開發(fā)心情,更能讓項目健壯性和擴(kuò)展性大大增強(qiáng)。
? 要求
- iOS 8.0+
- Xcode 8.0+
- Objective-C
? 測試 UI 什么樣子?
| 登錄視圖 | 示例展示 | 跳轉(zhuǎn)頁面 | 介紹頁面 |
? 安裝方法
安裝
在 iOS, 你需要在 Podfile 中添加.
source 'https://github.com/CocoaPods/Specs.git' platform :ios, '9.0' use_frameworks!# 提示組件框架pod 'SVProgressHUD', '~> 2.2.2'# 網(wǎng)絡(luò)請求框架pod 'YTKNetwork', '~> 2.0.3'# AOP面向切面pod 'Aspects', '~> 1.4.1'# 響應(yīng)函數(shù)式框架pod 'ReactiveObjC', '~> 3.0.0'# 路由組件化解耦pod 'JLRoutes', '~> 2.0.5'# 提示組件框架pod 'SVProgressHUD', '~> 2.2.2'# 自動布局pod 'Masonry', '~> 1.0.2' 復(fù)制代碼? 框架介紹
1.AOP 模式(Aspects-RunTime 代替基類)+ Category 方法交換
采用AOP思想,使用 Aspects 來完成替換 Controller ,View,ViewModel基類,和基類說拜拜
Casa反革命工程師 iOS應(yīng)用架構(gòu)談 view層的組織和調(diào)用方案 博客中提到一個疑問 是否有必要讓業(yè)務(wù)方統(tǒng)一派生ViewController
Casa大神回答是NO,原因如下
框架不需要通過繼承即能夠?qū)iewController進(jìn)行統(tǒng)一配置。業(yè)務(wù)即使脫離環(huán)境,也能夠跑完代碼,ViewController一旦放入框架環(huán)境,不需要添加額外的或者只需添加少量代碼,框架也能夠起到相應(yīng)的作用 對于本人來說 ,具備這點的吸引力,已經(jīng)足夠讓我有嘗試一番的心思了。
對于OC來說,方法攔截很容易就想到自帶的黑魔法方法調(diào)配 Method Swizzling, 至于為ViewController做動態(tài)配置,自然非Category莫屬了 Method Swizzling 業(yè)界已經(jīng)有非常成熟的三方庫 Aspects, 所以Demo代碼采用 Aspects 做方法攔截。
+ (void)load {[super load];[FKViewControllerIntercepter sharedInstance]; } // .... 單例初始化代碼- (instancetype)init {self = [super init];if (self) {/* 方法攔截 */// 攔截 viewDidLoad 方法[UIViewController aspect_hookSelector:@selector(viewDidLoad) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo>aspectInfo){[self _viewDidLoad:aspectInfo.instance];} error:nil];// 攔截 viewWillAppear:[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated){[self _viewWillAppear:animated controller:aspectInfo.instance];} error:NULL];}return self; } 復(fù)制代碼至于 Category 已經(jīng)非常熟悉了
@interface UIViewController (NonBase)/**去Model&&表征化參數(shù)列表*/ @property (nonatomic, strong) NSDictionary *params;/**ViewModel 屬性*/ @property (nonatomic, strong) id <FKViewControllerProtocol> viewModel;/**返回Controller的當(dāng)前bounds@param hasNav 是否有導(dǎo)航欄@param hasTabBar 是否有tabbar@return 坐標(biāo)*/ - (CGRect)fk_visibleBoundsShowNav:(BOOL)hasNav showTabBar:(BOOL)hasTabBar;/**隱藏鍵盤*/ - (void)fk_hideKeyBoard; @end 復(fù)制代碼至此,我們已經(jīng)實現(xiàn)了不繼承基類來實現(xiàn)對ViewController的配置,項目中的 View ViewModel 去基類原理如出一轍。
2.View層采用 MVVM 設(shè)計模式,使用 ReactiveObjC 進(jìn)行數(shù)據(jù)綁定
-MVC-
作為老牌思想MVC,大家早已耳熟能詳,MVC素有 Massive VC之稱,隨著業(yè)務(wù)增加,Controller將會越來越復(fù)雜,最終Controller會變成一個"神類", 即有網(wǎng)絡(luò)請求等代碼,又充斥著大量業(yè)務(wù)邏輯,所以為Controller減負(fù),在某些情況下變得勢在必行
-MVVM-
MVVM是基于胖Model的架構(gòu)思路建立的,然后在胖Model中拆出兩部分:Model和ViewModel (注:胖Model 是指包含了一些弱業(yè)務(wù)邏輯的Model) 胖Model實際上是為了減負(fù) Controller 而存在的,而 MVVM 是為了拆分胖Model , 最終目的都是為了減負(fù)Controller。
我們知道,蘋果MVC并沒有專門為網(wǎng)絡(luò)層代碼分專門的層級,按照以往習(xí)慣,大家都寫在了Controller 中,這也是Controller 變Massive得元兇之一,現(xiàn)在我們可以將網(wǎng)絡(luò)請求等諸如此類的代碼放到ViewModel中了 (文章后半部分將會描述ViewModel中的網(wǎng)絡(luò)請求)
-數(shù)據(jù)流向-
正常的網(wǎng)絡(luò)請求獲取數(shù)據(jù),然后更新View自然不必多說,那么如果View產(chǎn)生了數(shù)據(jù)要怎么把數(shù)據(jù)給到Model,由于View不直接持有ViewModel,所以我們需要有個橋梁 ReactiveCocoa, 通過 Signal 來和 ViewModel 通信,這個過程我們使用 通知 或者 Target-Action也可以實現(xiàn)相同的效果,只不過沒有 ReactiveCocoa 如此方便罷了
/* View -> ViewModel 傳遞數(shù)據(jù)示例 */ - (void)bindViewModel:(id<FKViewModelProtocol>)viewModel withParams:(NSDictionary *)params {if ([viewModel isKindOfClass:[FKLoginViewModel class]]){FKLoginViewModel *_viewModel = (FKLoginViewModel *)viewModel;// 綁定賬號 View -> ViewModel 傳遞數(shù)據(jù) @weakify(self);RAC(_viewModel, userAccount) = [[self.inputTextFiled.rac_textSignal takeUntil:self.rac_prepareForReuseSignal] map:^id _Nullable(NSString * _Nullable account) {@strongify(self);// 限制賬號長度if (account.length > 25) {self.inputTextFiled.text = [account substringToIndex:25];}return self.inputTextFiled.text;}];} } 復(fù)制代碼上面代碼給出了 View -> ViewModel 綁定的一個例子 具體一些詳情,可以直接看Demo MVVM一些總結(jié):
3.網(wǎng)絡(luò)層使用 YTKNetwork 配合 ReactiveCocoa 封裝網(wǎng)絡(luò)請求,解決如何交付數(shù)據(jù),交付什么樣的數(shù)據(jù)(去Model化)等問題
YTKNetwork 是猿題庫 iOS 研發(fā)團(tuán)隊基于 AFNetworking 封裝的 iOS 網(wǎng)絡(luò)庫,其實現(xiàn)了一套 High Level 的 API,提供了更高層次的網(wǎng)絡(luò)訪問抽象。
筆者對 YTKNetwork 進(jìn)行了一些封裝,結(jié)合 ReactiveCocoa,并提供 reFormatter 接口對服務(wù)器響應(yīng)數(shù)據(jù)重新處理,靈活交付給業(yè)務(wù)層。 接下來,本文會回答兩個問題
以什么方式將數(shù)據(jù)交付給業(yè)務(wù)層?
雖然 iOS應(yīng)用架構(gòu)談 網(wǎng)絡(luò)層設(shè)計方案 中 Casa大神寫到 盡量不要用block,應(yīng)該使用代理 的確,Block難以追蹤和定位錯誤,容易內(nèi)存泄漏, YTKNetwork 也提供代理方式回調(diào)
@protocol YTKRequestDelegate <NSObject>@optional /// Tell the delegate that the request has finished successfully. /// /// @param request The corresponding request. - (void)requestFinished:(__kindof YTKBaseRequest *)request;/// Tell the delegate that the request has failed. /// /// @param request The corresponding request. - (void)requestFailed:(__kindof YTKBaseRequest *)request;@end 復(fù)制代碼前文有說過,MVVM 并不等于 ReactiveCocoa , 但是想要體驗最純正的 ReactiveCocoa 還是Block較為酸爽,Demo中筆者兩者都給出了代碼, 大家可以自行選擇和斟酌哈 我們看一下 YTKNetwork 和 ReactiveCocoa 結(jié)合的代碼
- (RACSignal *)rac_requestSignal {[self stop];RACSignal *signal = [[RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {// 請求起飛[self startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {// 成功回調(diào)[subscriber sendNext:[request responseJSONObject]];[subscriber sendCompleted];} failure:^(__kindof YTKBaseRequest * _Nonnull request) {// 錯誤回調(diào)[subscriber sendError:[request error]];}];return [RACDisposable disposableWithBlock:^{// Signal銷毀 停止請求[self stop];}];}] takeUntil:[self rac_willDeallocSignal]];//設(shè)置名稱 便于調(diào)試if (DEBUG) {[signal setNameWithFormat:@"%@ -rac_xzwRequest", RACDescription(self)];}return signal; } 復(fù)制代碼寫了一個簡單的 Category FKBaseRequest+Rac.h ViewModel 中使用 RACCommand 封裝調(diào)用:
- (RACCommand *)loginCommand {if (!_loginCommand) {@weakify(self);_loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id _Nullable input) {@strongify(self);return [[[FKLoginRequest alloc] initWithUsr:self.userAccount pwd:self.password] rac_requestSignal];}];}return _loginCommand; } 復(fù)制代碼Block方式交付業(yè)務(wù)
FKLoginRequest *loginRequest = [[FKLoginRequest alloc] initWithUsr:self.userAccount pwd:self.password]; return [[[loginRequest rac_requestSignal] doNext:^(id _Nullable x) {// 解析數(shù)據(jù)[[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isLogin"];}] materialize]; 復(fù)制代碼Delegate方式交付業(yè)務(wù)
FKLoginRequest *loginRequest = [[FKLoginRequest alloc] initWithUsr:self.userAccount pwd:self.password]; // 數(shù)據(jù)請求響應(yīng)代理 通過代理回調(diào) loginRequest.delegate = self; return [loginRequest rac_requestSignal]; - (void)requestFinished:(__kindof YTKBaseRequest *)request {// 解析數(shù)據(jù)[[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"isLogin"]; } 復(fù)制代碼交付什么樣的數(shù)據(jù) ?
現(xiàn)在諸如 JSONModel ,YYModel 之類的Json轉(zhuǎn)Model的庫也非常多,大多數(shù)Json對象,網(wǎng)絡(luò)請求成功直接就被轉(zhuǎn)成Model了 然而 iOS應(yīng)用架構(gòu)談 網(wǎng)絡(luò)層設(shè)計方案 中給出了兩種有意思的交付思路
Casa文章中好處已經(jīng)寫得很詳細(xì)了,通過不同的 reformer 來重塑和交付不同的業(yè)務(wù)數(shù)據(jù),可以說是非常靈活了
使用 reformer 對數(shù)據(jù)進(jìn)行清洗
在網(wǎng)絡(luò)層封裝 FKBaseRequest.h 中 給出了 FKBaseRequestFeformDelegate 接口來重塑數(shù)據(jù)
@protocol FKBaseRequestFeformDelegate <NSObject>/**自定義解析器解析響應(yīng)參數(shù)@param request 當(dāng)前請求@param jsonResponse 響應(yīng)數(shù)據(jù)@return 自定reformat數(shù)據(jù)*/ - (id)request:(FKBaseRequest *)request reformJSONResponse:(id)jsonResponse;@end 然后在對應(yīng)的 reformer 對數(shù)據(jù)進(jìn)行重塑 - (id)request:(FKBaseRequest *)request reformJSONResponse:(id)jsonResponse {if([request isKindOfClass:FKLoginRequest.class]){// 在這里對json數(shù)據(jù)進(jìn)行重新格式化}return jsonResponse; } 復(fù)制代碼也可以直接在子類的 RequestManager 中覆蓋父類方法達(dá)到一樣的效果
/* FKLoginRequest.m */// 可以在這里對response 數(shù)據(jù)進(jìn)行重新格式化, 也可以使用delegate 設(shè)置 reformattor - (id)reformJSONResponse:(id)jsonResponse { } 復(fù)制代碼去特定對象表征 (去Model)
這思路可以說是業(yè)界的泥石流了 去Model也就是說,使用NSDictionary形式交付數(shù)據(jù),對于網(wǎng)絡(luò)層而言,只需要保持住原始數(shù)據(jù)即可,不需要主動轉(zhuǎn)化成數(shù)據(jù)原型 但是會存在一些小問題
Casa大神 提出了 使用EXTERN + Const 字符串形式,并建議字符串跟著reformer走,個人覺得很多時候API只需要一種解析格式,所以Demo跟著 APIManager 走,其他情況下常量字符串建議聽從 Casa大神 的建議, 常量定義:
/* FKBaseRequest.h */ // 登錄token key FOUNDATION_EXTERN NSString *FKLoginAccessTokenKey;/* FKBaseRequest.m */ NSString *FKLoginAccessTokenKey = @"accessToken"; 復(fù)制代碼在 .h 和 .m 文件中要同時寫太多代碼,我們也可以使用局部常量的形式,只要在 .h 文件中定義即可
// 也可以寫成 局部常量形式 static const NSString *FKLoginAccessTokenKey2 = @"accessToken"; 最終那么我們的reformer可能會變成這樣子 - (id)request:(FKBaseRequest *)request reformJSONResponse:(id)jsonResponse {if([request isKindOfClass:FKLoginRequest.class]){// 在這里對json數(shù)據(jù)進(jìn)行重新格式化return @{FKLoginAccessTokenKey : jsonResponse[@"token"],};}return jsonResponse; } 復(fù)制代碼復(fù)雜和多樣的數(shù)據(jù)結(jié)構(gòu)如何解析? 有時候,reformer 交付過來的數(shù)據(jù),我們需要解析的可能是字符串類型,也可能是NSNumber類型,也有可能是數(shù)組 為此,筆者提供了一系列 Encode Decode方法,來降低解析的復(fù)雜度和安全性
// NSDictionary -> NSString FK_EXTERN NSString* DecodeObjectFromDic(NSDictionary *dic, NSString *key); // NSArray + index -> id FK_EXTERN id DecodeSafeObjectAtIndex(NSArray *arr, NSInteger index); // NSDictionary -> NSString FK_EXTERN NSString * DecodeStringFromDic(NSDictionary *dic, NSString *key); // NSDictionary -> NSString ? NSString : defaultStr FK_EXTERN NSString* DecodeDefaultStrFromDic(NSDictionary *dic, NSString *key,NSString * defaultStr); // NSDictionary -> NSNumber FK_EXTERN NSNumber * DecodeNumberFromDic(NSDictionary *dic, NSString *key); // NSDictionary -> NSDictionary FK_EXTERN NSDictionary *DecodeDicFromDic(NSDictionary *dic, NSString *key); // NSDictionary -> NSArray FK_EXTERN NSArray *DecodeArrayFromDic(NSDictionary *dic, NSString *key); FK_EXTERN NSArray *DecodeArrayFromDicUsingParseBlock(NSDictionary *dic, NSString *key, id(^parseBlock)(NSDictionary *innerDic)); // (nonull Key: nonull NSString) -> NSMutableDictionary FK_EXTERN void EncodeUnEmptyStrObjctToDic(NSMutableDictionary *dic,NSString *object, NSString *key); // nonull objec -> NSMutableArray FK_EXTERN void EncodeUnEmptyObjctToArray(NSMutableArray *arr,id object); // (nonull (Key ? key : defaultStr) : nonull Value) -> NSMutableDictionary FK_EXTERN void EncodeDefaultStrObjctToDic(NSMutableDictionary *dic,NSString *object, NSString *key,NSString * defaultStr); // (nonull Key: nonull object) -> NSMutableDictionary FK_EXTERN void EncodeUnEmptyObjctToDic(NSMutableDictionary *dic,NSObject *object, NSString *key); 復(fù)制代碼我們的reformer可以寫成這樣子
- (id)request:(FKBaseRequest *)request reformJSONResponse:(id)jsonResponse {if([request isKindOfClass:FKLoginRequest.class]){// 在這里對json數(shù)據(jù)進(jìn)行重新格式化return @{FKLoginAccessTokenKey : DecodeStringFromDic(jsonResponse, @"token")};}return jsonResponse; } 復(fù)制代碼解析有可能是這樣子
NSString *token = DecodeStringFromDic(jsonResponse, FKLoginAccessTokenKey) 復(fù)制代碼好了,至此我們解決了兩個問題
4.采用 JLRoutes 路由對應(yīng)用進(jìn)行組件化解耦
帶著問題思考如何才能設(shè)計出最好的組件化路由:
- 1)3D-Touch功能或者點擊推送消息,要求外部跳轉(zhuǎn)到App內(nèi)部一個很深層次的一個界面。
- 2)自家的一系列App之間如何相互跳轉(zhuǎn)?
- 3)如何解除App組件之間和App頁面之間的耦合性?
- 4)如何能統(tǒng)一iOS和Android兩端的頁面跳轉(zhuǎn)邏輯?甚至如何能統(tǒng)一三端的請求資源的方式?
- 5)如果使用了動態(tài)下發(fā)配置文件來配置App的跳轉(zhuǎn)邏輯,那么如果做到iOS和Android兩邊只要共用一套配置文件?
- 6)如果App出現(xiàn)bug了,如何不用JSPatch,就能做到簡單的熱修復(fù)功能?
- 7)如何在每個組件間調(diào)用和頁面跳轉(zhuǎn)時都進(jìn)行埋點統(tǒng)計?每個跳轉(zhuǎn)的地方都手寫代碼埋點?利用Runtime AOP ?
- 8)如何在每個組件間調(diào)用的過程中,加入調(diào)用的邏輯檢查,令牌機(jī)制,配合灰度進(jìn)行風(fēng)控邏輯?
- 9)如何在App任何界面都可以調(diào)用同一個界面或者同一個組件?只能在AppDelegate里面注冊單例來實現(xiàn)?
iOS應(yīng)用架構(gòu)談 組件化方案 一文中 Casa 針對 蘑菇街組件化 提出了質(zhì)疑,質(zhì)疑點主要在這幾方面
對于 App啟動時組件需要注冊URL 顧慮主要在于,注冊的URL需要在應(yīng)用生存周期內(nèi)常駐內(nèi)存,如果是注冊Class還好些,如果注冊的是實例,消耗的內(nèi)存就非常可觀了
NSString *const FKNavPushRoute = @"/com_madao_navPush/:viewController"; NSString *const FKNavPresentRoute = @"/com_madao_navPresent/:viewController"; NSString *const FKNavStoryBoardPushRoute = @"/com_madao_navStoryboardPush/:viewController"; NSString *const FKComponentsCallBackRoute = @"/com_madao_callBack/*"; 復(fù)制代碼而且JLRoutes 還支持 * 來進(jìn)行通配,路由表如何編寫大家可以自由發(fā)揮 對應(yīng)的路由事件 handler
// push // 路由 /com_madao_navPush/:viewController [[JLRoutes globalRoutes] addRoute:FKNavPushRoute handler:^BOOL(NSDictionary<NSString *,id> * _Nonnull parameters) {dispatch_async(dispatch_get_main_queue(), ^{[self _handlerSceneWithPresent:NO parameters:parameters];});return YES; }];// present // 路由 /com_madao_navPresent/:viewController [[JLRoutes globalRoutes] addRoute:FKNavPresentRoute handler:^BOOL(NSDictionary<NSString *,id> * _Nonnull parameters) {dispatch_async(dispatch_get_main_queue(), ^{[self _handlerSceneWithPresent:YES parameters:parameters];});return YES; }]; /// 處理跳轉(zhuǎn)事件 - (void)_handlerSceneWithPresent:(BOOL)isPresent parameters:(NSDictionary *)parameters {// 當(dāng)前控制器NSString *controllerName = [parameters objectForKey:FKControllerNameRouteParam];UIViewController *currentVC = [self _currentViewController];UIViewController *toVC = [[NSClassFromString(controllerName) alloc] init];toVC.params = parameters;if (currentVC && currentVC.navigationController) {if (isPresent) {[currentVC.navigationController presentViewController:toVC animated:YES completion:nil];}else{[currentVC.navigationController pushViewController:toVC animated:YES];}} } 復(fù)制代碼通過URL中傳入的組件名動態(tài)注冊,處理相應(yīng)跳轉(zhuǎn)事件,并不需要每個組件一一注冊 使用URL路由,必然URL會散落到代碼各個地方
NSString *key = @"key"; NSString *value = @"value"; NSString *url = [NSString stringWithFormat:@"/com_madao_navPush/%@?%@=%@", NSStringFromClass(ViewController.class), key, value]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]]; 復(fù)制代碼諸如此類丑陋的代碼,散落在各個地方的話簡直會讓人頭皮發(fā)麻, 所以筆者在 JLRoutes+GenerateURL.h 寫了一些 Helper方法
/**避免 URL 散落各處, 集中生成URL@param pattern 匹配模式@param parameters 附帶參數(shù)@return URL字符串*/ + (NSString *)fk_generateURLWithPattern:(NSString *)pattern parameters:(NSArray *)parameters;/**避免 URL 散落各處, 集中生成URL額外參數(shù)將被 ?key=value&key2=value2 樣式給出@param pattern 匹配模式@param parameters 附加參數(shù)@param extraParameters 額外參數(shù)@return URL字符串*/ + (NSString *)fk_generateURLWithPattern:(NSString *)pattern parameters:(NSArray *)parameters extraParameters:(NSDictionary *)extraParameters;/**解析NSURL對象中的請求參數(shù) http://madao?param1=value1?m2=value2 解析成 @{param1:value1, param2:value2}@param URL NSURL對象@return URL字符串*/ + (NSDictionary *)fk_parseParamsWithURL:(NSURL *)URL;/**將參數(shù)對象進(jìn)行url編碼將@{param1:value1, param2:value2} 轉(zhuǎn)換成 ?param1=value1¶m2=value2@param dic 參數(shù)對象@return URL字符串*/ + (NSString *)fk_mapDictionaryToURLQueryString:(NSDictionary *)dic; 復(fù)制代碼宏定義Helper
([NSString stringWithFormat: @"%@:/%@", \ Schema, \ path]) ([NSURL URLWithString: \ JLRGenRoute(Schema, path)]) 復(fù)制代碼最終我們的調(diào)用可以變成
NSString *router = [JLRoutes fk_generateURLWithPattern:FKNavPushRoute parameters:@[NSStringFromClass(ViewController.class)] extraParameters:nil]; [[UIApplication sharedApplication] openURL:JLRGenRouteURL(FKDefaultRouteSchema, router)]; 復(fù)制代碼? 整理制作
Casa Taloyum:https://casatwy.com/modulization_in_action.html
簡書博客:http://www.jianshu.com/p/921dd65e79cb
? 聯(lián)系
- 微信 : WhatsXie
- 郵件 : ReverseScale@iCloud.com
- 博客 : https://reversescale.github.io
- 源碼 : https://github.com/ReverseScale/OCTemplate
總結(jié)
以上是生活随笔為你收集整理的走在技术前沿的 iOS 架构实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第四章:滚动堆栈(1)
- 下一篇: maven+nexus搭建maven仓库