
簡介
在 iOS 工程中,AppDelegate 往往有上千行甚至幾千行,這會給維護帶來諸多麻煩。比如說,老闆想在 HomeViewController 出現前彈出廣告並停留幾秒,你就得加入插入廣告的邏輯;又比如說,老闆想在啟動時做個請求,判斷某個開關是否打開——這樣就會在 AppDelegate 中塞入很多相關又不相關的程式碼。
在 AppDelegate 中,- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 會在 app 開始運行時被呼叫。在這個方法裡,我們往往會渲染 window、註冊第三方監控庫、加入基本頁面跳轉邏輯。
下面是一個常見專案中的 didFinishLaunchingWithOptions:
// objective-c語言 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if (!([ADeanUserDataManager sharedManager].userName != nil && [ADeanUserDataManager sharedManager].userName.length > 0 && [ADeanUserDataManager sharedManager].userPassword != nil && [ADeanUserDataManager sharedManager].userPassword.length > 0)) { // 用戶名、密碼為空時候強制為未登錄 [ADeanUserDataManager sharedManager].isUserLogined = @NO; } self.window.rootViewController = self.tabbarController; [self.window makeKeyAndVisible]; // 基本頁面跳轉邏輯 /*--------------------------------------*/ if ([[ADeanUserDataManager sharedManager].everLaunched boolValue] == NO) { //是否是第一次啟動判斷 [ADeanUserDataManager sharedManager].everLaunched = [NSNumber numberWithBool:YES]; [self.window addSubview:self.helpViewController.view]; } /*--------------------------------------*/ // 注冊第三方庫 /*--------------------------------------*/ // 注冊Crash統計 -- Crashlytics [Fabric with:@[[Crashlytics class]]]; [MobClick startWithAppkey:UMENG_APPKEY]; [MobClick setCrashReportEnabled:NO]; // 關掉MobClick Crash Report收集開關 #ifdef ADeanForTest [MobClick setCrashReportEnabled:YES]; // 打開MobClick Crash Report收集開關 [MobClick setLogEnabled:YES]; #endif [ShareSDK registerApp:ShareSDKAppKey]; //新浪 [ShareSDK connectSinaWeiboWithAppKey:SinaAppKey appSecret:SinaAppSecret redirectUri:SinaRedirectUri]; //新浪微博客戶端應用 [ShareSDK connectSinaWeiboWithAppKey:SinaAppKey appSecret:SinaAppSecret redirectUri:SinaRedirectUri weiboSDKCls:[WeiboSDK class]]; #if TARGET_IPHONE_SIMULATOR #else //QQ好友 [ShareSDK connectQQWithQZoneAppKey:QZoneAppKey qqApiInterfaceCls:[QQApiInterface class] tencentOAuthCls:[TencentOAuth class]]; #endif //微信朋友圈 [ShareSDK connectWeChatSessionWithAppId:WeiXinAppID wechatCls:[WXApi class]]; //微信好友 [ShareSDK connectWeChatTimelineWithAppId:WeiXinAppID wechatCls:[WXApi class]]; [MiPushSDK registerMiPush:self type:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) connect:YES]; /*--------------------------------------*/ // 其他邏輯 [self registerRemotePushNotification]; [self getSwitchInfoFromService]; [self appIntegrityCheck]; [self appSecurityCheck] ...... return YES; }下面我們來看看,有什麼好辦法可以為 AppDelegate 瘦身,加強程式碼的可讀性與可維護性,並把程式碼放到合適的地方。
函數模塊化
上述 didFinishLaunchingWithOptions 可按功能邏輯劃分為三類:處理啟動邏輯、註冊第三方庫、處理其他邏輯。這樣就能優化為:
// objective-c語言 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if (!([ADeanUserDataManager sharedManager].userName != nil && [ADeanUserDataManager sharedManager].userName.length > 0 && [ADeanUserDataManager sharedManager].userPassword != nil && [ADeanUserDataManager sharedManager].userPassword.length > 0)) { // 用戶名、密碼為空時候強制為未登錄 [ADeanUserDataManager sharedManager].isUserLogined = @NO; } self.window.rootViewController = self.tabbarController; [self.window makeKeyAndVisible]; // 基本頁面跳轉邏輯 [self baseViewJumpLogic]; // 注冊第三方庫 [self registThirdPart]; // 其他邏輯 [self handleOtherLogic] return YES; } - (void)baseViewJumpLogic { if ([[ADeanUserDataManager sharedManager].everLaunched boolValue] == NO) { //是否是第一次啟動判斷 [ADeanUserDataManager sharedManager].everLaunched = [NSNumber numberWithBool:YES]; [self.window addSubview:self.helpViewController.view]; } } - (void)registThirdPart { // 注冊Crash統計 -- Crashlytics [Fabric with:@[[Crashlytics class]]]; [MobClick startWithAppkey:UMENG_APPKEY]; [MobClick setCrashReportEnabled:NO]; // 關掉MobClick Crash Report收集開關 #ifdef ADeanForTest [MobClick setCrashReportEnabled:YES]; // 打開MobClick Crash Report收集開關 [MobClick setLogEnabled:YES]; #endif [ShareSDK registerApp:ShareSDKAppKey]; //新浪 [ShareSDK connectSinaWeiboWithAppKey:SinaAppKey appSecret:SinaAppSecret redirectUri:SinaRedirectUri]; //新浪微博客戶端應用 [ShareSDK connectSinaWeiboWithAppKey:SinaAppKey appSecret:SinaAppSecret redirectUri:SinaRedirectUri weiboSDKCls:[WeiboSDK class]]; #if TARGET_IPHONE_SIMULATOR #else //QQ好友 [ShareSDK connectQQWithQZoneAppKey:QZoneAppKey qqApiInterfaceCls:[QQApiInterface class] tencentOAuthCls:[TencentOAuth class]]; #endif //微信朋友圈 [ShareSDK connectWeChatSessionWithAppId:WeiXinAppID wechatCls:[WXApi class]]; //微信好友 [ShareSDK connectWeChatTimelineWithAppId:WeiXinAppID wechatCls:[WXApi class]]; [MiPushSDK registerMiPush:self type:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) connect:YES]; } - (void)handleOtherLogic { [self registerRemotePushNotification]; [self getSwitchInfoFromService]; [self appIntegrityCheck]; [self appSecurityCheck] ...... }模塊化後,程式碼瞬間變得易讀很多,需要改什麼也可以直接去對應的模塊添加。但這僅僅是把程式碼的順序調整一下,把相同功能的程式碼抽到一個函數中,程式碼行數並沒有減少,所有功能還是糅合在同一個 .m 裡。
類模塊化
很多其他邏輯屬於業務邏輯,可以抽離到業務 Model 中,透過類模塊化便捷使用。這樣就能優化為:
// objective-c語言 #import "ADeanAppCheck.h" #import "ADeanSwitches.h" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if (!([ADeanUserDataManager sharedManager].userName != nil && [ADeanUserDataManager sharedManager].userName.length > 0 && [ADeanUserDataManager sharedManager].userPassword != nil && [ADeanUserDataManager sharedManager].userPassword.length > 0)) { // 用戶名、密碼為空時候強制為未登錄 [ADeanUserDataManager sharedManager].isUserLogined = @NO; } self.window.rootViewController = self.tabbarController; [self.window makeKeyAndVisible]; // 基本頁面跳轉邏輯 [self baseViewJumpLogic]; // 注冊第三方庫 [self registThirdPart]; // 其他邏輯 [self handleOtherLogic] return YES; } - (void)handleOtherLogic { [ADeanAppCheck appInfoCheck]; // Integrity & Security Check [ADeanSwitches appSwitchInit]; // Get Switch From Service ...... }分類模塊化
先拋個問題:分類中是否可以定義變量?
如果不知道,可以參考:iOS 分類中透過 runtime 添加動態屬性。
分類能做到的事情主要是:即使在你不知道一個類別源碼的情況下,向這個類別添加擴充的方法。這裡我們主要是把對外開放的方法和一部分變量拿到分類中處理,進一步輕量化 AppDelegate 本身的程式碼量。
// objective-c語言 // ADeanAppDelegate+Light.h文件 #import "AppDelegate.h" @interface ADeanAppDelegate (Light) @property (nonatomic, strong) UITabbarController *tabbarController; /*! @brief 全局appDeleaget */ + (AppDelegate *)appDelegate; /*! @method @brief 關閉系統鍵盤 */ + (void)closeKeyWindow; @end // objective-c語言 // ADeanAppDelegate+Light.m文件 #import "ADeanAppDelegate+Light.h" - (UITabbarController *)tabbarController { UITabbarController *tabbarController = objc_getAssociatedObject(self, &kTabbarControllerObjectKey); if (!tabbarController) { tabbarController = [[UITabbarController alloc] init]; objc_setAssociatedObject(self, &kTabbarControllerObjectKey, tabbarController, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } return tabbarController; } - (void)setTabbarController:(UITabbarController *)tabbarController { objc_setAssociatedObject(self, &kTabbarControllerObjectKey, tabbarController, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } + (AppDelegate *)appDelegate { return (AppDelegate *)[[UIApplication sharedApplication] delegate]; } + (void)closeKeyWindow { [[UIApplication sharedApplication].keyWindow endEditing:YES]; } 這樣在AppDelegate中,對外開放的方法和部分變量可以抽離到分類中去。也可以根據作用定義不同的AppDelegate分類: #“ADeanAppDelegate+View.h” #“ADeanAppDelegate+Controller.h” #“ADeanAppDelegate+Method.h” …這樣程式碼結構會更加清晰明瞭。抽出來的 AppDelegate 只剩下註冊第三方庫了,因為第三方庫很多需要在 didFinishLaunchingWithOptions 中運行,正常的方法就很難做到。
Method Swizzling 化
Method Swizzling 是改變一個 selector 實際實現的技術,關於它的概念與原理,網上資料很多。這裡以 viewWillAppear 為例,講解 Method Swizzling 的基本用法。
#import "ADeanAppDelegate+Hook.h" #import "ADeanMethodSwizzling.h" #import "MobClick.h" #import "WXApi.h" #import "WeiboSDK.h" #import #import #import #if TARGET_IPHONE_SIMULATOR #else #import #import #import #endif @implementation ADeanAppDelegate (Hook) + (void)initialize { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [self adean_AppDelegateHook]; }); } + (void)adean_AppDelegateHook { SwizzlingMethod([ADeanAppDelegate class], @selector(application:didFinishLaunchingWithOptions:), @selector(adean_application:didFinishLaunchingWithOptions:)); SwizzlingMethod([ADeanAppDelegate class], @selector(application:handleOpenURL:), @selector(adean_application:handleOpenURL:)); SwizzlingMethod([ADeanAppDelegate class], @selector(application:openURL:sourceApplication:annotation:), @selector(adean_application:openURL:sourceApplication:annotation:)); SwizzlingMethod([ADeanAppDelegate class], @selector(applicationDidReceiveMemoryWarning:), @selector(adean_applicationDidReceiveMemoryWarning:)); } #pragma mark - Method Swizzling - (BOOL)adean_application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 耗時的操作 // 注冊Crash統計 -- Crashlytics [Fabric with:@[[Crashlytics class]]]; // 友盟統計 [MobClick startWithAppkey:UMENG_APPKEY]; [MobClick setCrashReportEnabled:NO]; // 關掉MobClick Crash Report收集開關 #ifdef ADeanForTest [MobClick setCrashReportEnabled:YES]; // 打開MobClick Crash Report收集開關 [MobClick setLogEnabled:YES]; #endif [ShareSDK registerApp:ShareSDKAppKey]; //新浪 [ShareSDK connectSinaWeiboWithAppKey:SinaAppKey appSecret:SinaAppSecret redirectUri:SinaRedirectUri]; //新浪微博客戶端應用 [ShareSDK connectSinaWeiboWithAppKey:SinaAppKey appSecret:SinaAppSecret redirectUri:SinaRedirectUri weiboSDKCls:[WeiboSDK class]]; #if TARGET_IPHONE_SIMULATOR #else //QQ好友 [ShareSDK connectQQWithQZoneAppKey:QZoneAppKey qqApiInterfaceCls:[QQApiInterface class] tencentOAuthCls:[TencentOAuth class]]; #endif //微信朋友圈 [ShareSDK connectWeChatSessionWithAppId:WeiXinAppID wechatCls:[WXApi class]]; //微信好友 [ShareSDK connectWeChatTimelineWithAppId:WeiXinAppID wechatCls:[WXApi class]]; }); return [self adean_application:application didFinishLaunchingWithOptions:launchOptions]; } - (BOOL)adean_application:(UIApplication *)application handleOpenURL:(NSURL *)url { [ShareSDK handleOpenURL:url wxDelegate:self]; return [self adean_application:application handleOpenURL:url]; } - (BOOL)adean_application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { [ShareSDK handleOpenURL:url sourceApplication:sourceApplication annotation:annotation wxDelegate:self]; return [self adean_application:application openURL:url sourceApplication:sourceApplication annotation:annotation]; } - (void)adean_applicationDidReceiveMemoryWarning:(UIApplication *)application { [self adean_applicationDidReceiveMemoryWarning:application]; } @end這下再去看 AppDelegate 檔案,程式碼就不超過 200 行了。
小結
Method Swizzling 常見的應用場景:
1. 用於記錄或存儲,比如記錄 ViewController 進入次數、按鈕點擊事件、ViewController 的停留時間等等,可透過 Runtime 取得具體的 ViewController、按鈕資訊,然後傳給伺服器。
2. 添加需要而系統沒提供的方法,比如修改 Statusbar 顏色。
3. 用於輕量化、模塊化處理,如上文介紹的程式碼輕量化。
Method Swizzling 是一把雙刃劍,需要正確理解它的使用。
分類增加變量的使用場景:
1. 繼承過多時,可以透過分類減少繼承層級,清晰流程框架。比如 ViewController 可能需要互相衝突的事件,單一父類會導致邏輯複雜;這時可以透過分類簡化邏輯,不同的 ViewController 引用不同的分類。
2. 擴充類屬性。
以上我們學習了一些瘦身的技巧,希望透過這些方法寫出可讀性更高、可維護性更高的程式碼。
提醒:
本文涉及到的 Demo 已經放到 GitHub 上了。Demo 可能與本文有點出入,部分函數命名跟文章中不一致。