前言:什麼是Method Swizzling,在iOS開發中它有什麼做用?安全
簡單來講咱們主要是使用Method Swizzling來把系統的方法交換爲咱們本身的方法,從而給系統方法添加一些咱們想要的功能。該篇文章主要列舉Method Swizzling在開發中的一些現實用例,同時文中也有補充讀者的一些疑點。但願閱讀文章的朋友們也能夠提供一些文中還沒有舉出的例子,本文持續更新中。性能優化
目前已更新實例彙總:網絡
Method Swizzling通用方法封裝多線程
在列舉以前,咱們能夠將Method Swizzling功能封裝爲類方法,做爲NSObject的類別,這樣咱們後續調用也會方便些。app
#import <Foundation/Foundation.h> #import <objc/runtime.h> @interface NSObject (Swizzling) + (void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector bySwizzledSelector:(SEL)swizzledSelector; @end
#import "NSObject+Swizzling.h" @implementation NSObject (Swizzling) + (void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector bySwizzledSelector:(SEL)swizzledSelector{ Class class = [self class]; //原有方法 Method originalMethod = class_getInstanceMethod(class, originalSelector); //替換原有方法的新方法 Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); //先嚐試給源SEL添加IMP,這裏是爲了不源SEL沒有實現IMP的狀況 BOOL didAddMethod = class_addMethod(class,originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)); if (didAddMethod) {//添加成功:說明源SEL沒有實現IMP,將源SEL的IMP替換到交換SEL的IMP class_replaceMethod(class,swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else {//添加失敗:說明源SEL已經有IMP,直接將兩個SEL的IMP交換便可 method_exchangeImplementations(originalMethod, swizzledMethod); } } @end
⚠️補充知識點jsp
SEL、Method、IMP的含義及區別ide
在運行時,類(Class)維護了一個消息分發列表來解決消息的正確發送。每個消息列表的入口是一個方法(Method),這個方法映射了一對鍵值對,其中鍵是這個方法的名字(SEL),值是指向這個方法實現的函數指針 implementation(IMP)。
僞代碼表示:函數
Class { MethodList ( Method{ SEL:IMP; } Method{ SEL:IMP; } ); };
Method Swizzling就是改變類的消息分發列表來讓消息解析時從一個選擇器(SEL)對應到另一個的實現(IMP),同時將原始的方法實現混淆到一個新的選擇器(SEL)。性能
爲何要添加didAddMethod判斷?字體
先嚐試添加原SEL實際上是爲了作一層保護,由於若是這個類沒有實現originalSelector,但其父類實現了,那class_getInstanceMethod會返回父類的方法。這樣method_exchangeImplementations替換的是父類的那個方法,這固然不是咱們想要的。因此咱們先嚐試添加 orginalSelector,若是已經存在,再用 method_exchangeImplementations 把原方法的實現跟新的方法實現給交換掉。
若是理解還不夠透徹,咱們能夠進入runtime.h中查看class_addMethod源碼解釋:
/** * Adds a new method to a class with a given name and implementation. * * @param cls The class to which to add a method. * @param name A selector that specifies the name of the method being added. * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd. * @param types An array of characters that describe the types of the arguments to the method. * * @return YES if the method was added successfully, otherwise NO * (for example, the class already contains a method implementation with that name). * * @note class_addMethod will add an override of a superclass's implementation, * but will not replace an existing implementation in this class. * To change an existing implementation, use method_setImplementation. */
大概的意思就是咱們能夠經過class_addMethod爲一個類添加方法(包括方法名稱(SEL)和方法的實現(IMP)),返回值爲BOOL類型,表示方法是否成功添加。須要注意的地方是class_addMethod會添加一個覆蓋父類的實現,但不會取代原有類的實現。也就是說若是class_addMethod返回YES,說明子類中沒有方法originalSelector,經過class_addMethod爲其添加了方法originalSelector,並使其實現(IMP)爲咱們想要替換的實現。
class_addMethod(class,originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
同時再將原有的實現(IMP)替換到swizzledMethod方法上,
class_replaceMethod(class,swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
從而實現了方法的交換,而且未影響父類方法的實現。反之若是class_addMethod返回NO,說明子類中自己就具備方法originalSelector的實現,直接調用交換便可。
method_exchangeImplementations(originalMethod, swizzledMethod);
這一部份內容比較繞口,但願你們能夠耐下心來仔細反覆閱讀。
-------------------------------實例列舉-------------------------------
實例一:替換ViewController生命週期方法
App跳轉到某具備網絡請求的界面時,爲了用戶體驗效果常會添加加載欄或進度條來顯示當前請求狀況或進度。這種界面都會存在這樣一個問題,在請求較慢時,用戶手動退出界面,這時候須要去除加載欄。
固然能夠依次在每一個界面的viewWillDisappear方法中添加去除方法,但若是相似的界面過多,一味的複製粘貼也不是方法。這時候就能體現Method Swizzling的做用了,咱們能夠替換系統的viewWillDisappear方法,使得每當執行該方法時即自動去除加載欄。
#import "UIViewController+Swizzling.h" #import "NSObject+Swizzling.h" @implementation UIViewController (Swizzling) + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [self methodSwizzlingWithOriginalSelector:@selector(viewWillDisappear:) bySwizzledSelector:@selector(sure_viewWillDisappear:)]; }); } - (void)sure_viewWillDisappear:(BOOL)animated { [self sure_viewWillDisappear:animated]; [SVProgressHUD dismiss]; }
代碼如上,這樣就不用考慮界面是否移除加載欄的問題了。補充一點,一般咱們也會在生命週期方法中設置默認界面背景顏色,因若背景顏色默認爲透明對App的性能也有必定影響,這你們能夠在UIKit性能優化那篇文章中查閱。但相似該類操做也能夠書寫在通用類中,因此具體使用還要靠本身定奪。
⚠️補充知識點
爲何方法交換調用在+load方法中?
在Objective-C runtime會自動調用兩個類方法,分別爲+load與+ initialize。+load 方法是在類被加載的時候調用的,也就是必定會被調用。而+initialize方法是在類或它的子類收到第一條消息以前被調用的,這裏所指的消息包括實例方法和類方法的調用。也就是說+initialize方法是以懶加載的方式被調用的,若是程序一直沒有給某個類或它的子類發送消息,那麼這個類的+initialize方法是永遠不會被調用的。此外+load方法還有一個很是重要的特性,那就是子類、父類和分類中的+load方法的實現是被區別對待的。換句話說在 Objective-C runtime自動調用+load方法時,分類中的+load方法並不會對主類中的+load方法形成覆蓋。綜上所述,+load 方法是實現 Method Swizzling 邏輯的最佳「場所」。如需更深刻理解,可參考Objective-C 深刻理解 +load 和 +initialize。爲何方法交換要在dispatch_once中執行?
方法交換應該要線程安全,並且保證在任何狀況下(多線程環境,或者被其餘人手動再次調用+load方法)只交換一次,防止再次調用又將方法交換回來。除非只是臨時交換使用,在使用完成後又交換回來。 最經常使用的解決方案是在+load方法中使用dispatch_once來保證交換是安全的。以前有讀者反饋+load方法自己即爲線程安全,爲何仍需添加dispatch_once,其緣由就在於+load方法自己沒法保證其中代碼只被執行一次。爲何沒有發生死循環?
必定有不少讀者有疑惑,爲何sure_viewWillDisappear方法中的代碼沒有發生遞歸死循環。其緣由很簡單,由於方法已經執行過交換,調用[self sure_viewWillDisappear:animated]本質是在調用原有方法viewWillDisappear,反而若是咱們在方法中調用[self viewWillDisappear:animated]才真的會發生死循環。是否是很繞?仔細看看。實例二:解決獲取索引、添加、刪除元素越界崩潰問題
對於NSArray、NSDictionary、NSMutableArray、NSMutableDictionary難免會進行索引訪問、添加、刪除元素的操做,越界問題也是很常見,這時咱們能夠經過Method Swizzling解決這些問題,越界給予提示防止崩潰。
這裏以NSMutableArray爲例說明
#import "NSMutableArray+Swizzling.h" #import "NSObject+Swizzling.h" @implementation NSMutableArray (Swizzling) + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(removeObject:) bySwizzledSelector:@selector(safeRemoveObject:) ]; [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(addObject:) bySwizzledSelector:@selector(safeAddObject:)]; [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(removeObjectAtIndex:) bySwizzledSelector:@selector(safeRemoveObjectAtIndex:)]; [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(insertObject:atIndex:) bySwizzledSelector:@selector(safeInsertObject:atIndex:)]; [objc_getClass("__NSArrayM") methodSwizzlingWithOriginalSelector:@selector(objectAtIndex:) bySwizzledSelector:@selector(safeObjectAtIndex:)]; }); } - (void)safeAddObject:(id)obj { if (obj == nil) { NSLog(@"%s can add nil object into NSMutableArray", __FUNCTION__); } else { [self safeAddObject:obj]; } } - (void)safeRemoveObject:(id)obj { if (obj == nil) { NSLog(@"%s call -removeObject:, but argument obj is nil", __FUNCTION__); return; } [self safeRemoveObject:obj]; } - (void)safeInsertObject:(id)anObject atIndex:(NSUInteger)index { if (anObject == nil) { NSLog(@"%s can't insert nil into NSMutableArray", __FUNCTION__); } else if (index > self.count) { NSLog(@"%s index is invalid", __FUNCTION__); } else { [self safeInsertObject:anObject atIndex:index]; } } - (id)safeObjectAtIndex:(NSUInteger)index { if (self.count == 0) { NSLog(@"%s can't get any object from an empty array", __FUNCTION__); return nil; } if (index > self.count) { NSLog(@"%s index out of bounds in array", __FUNCTION__); return nil; } return [self safeObjectAtIndex:index]; } - (void)safeRemoveObjectAtIndex:(NSUInteger)index { if (self.count <= 0) { NSLog(@"%s can't get any object from an empty array", __FUNCTION__); return; } if (index >= self.count) { NSLog(@"%s index out of bound", __FUNCTION__); return; } [self safeRemoveObjectAtIndex:index]; } @end
對應你們能夠觸類旁通,相應的實現添加、刪除等,以及NSArray、NSDictionary等操做,因代碼篇幅較大,這裏就不一一書寫了。
這裏沒有使用self來調用,而是使用objc_getClass("__NSArrayM")來調用的。由於NSMutableArray的真實類只能經過後者來獲取,而不能經過[self class]來獲取,而method swizzling只對真實的類起做用。這裏就涉及到一個小知識點:類簇。補充以上對象對應類簇表。
類簇表.png
實例三:防止按鈕重複暴力點擊
程序中大量按鈕沒有作連續響應的校驗,連續點擊出現了不少沒必要要的問題,例如發表帖子操做,用戶手快點擊屢次,就會致使同一帖子發佈屢次。
#import <UIKit/UIKit.h> //默認時間間隔 #define defaultInterval 1 @interface UIButton (Swizzling) //點擊間隔 @property (nonatomic, assign) NSTimeInterval timeInterval; //用於設置單個按鈕不須要被hook @property (nonatomic, assign) BOOL isIgnore; @end
#import "UIButton+Swizzling.h" #import "NSObject+Swizzling.h" @implementation UIButton (Swizzling) + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [self methodSwizzlingWithOriginalSelector:@selector(sendAction:to:forEvent:) bySwizzledSelector:@selector(sure_SendAction:to:forEvent:)]; }); } - (NSTimeInterval)timeInterval{ return [objc_getAssociatedObject(self, _cmd) doubleValue]; } - (void)setTimeInterval:(NSTimeInterval)timeInterval{ objc_setAssociatedObject(self, @selector(timeInterval), @(timeInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } //當按鈕點擊事件sendAction 時將會執行sure_SendAction - (void)sure_SendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{ if (self.isIgnore) { //不須要被hook [self sure_SendAction:action to:target forEvent:event]; return; } if ([NSStringFromClass(self.class) isEqualToString:@"UIButton"]) { self.timeInterval =self.timeInterval == 0 ?defaultInterval:self.timeInterval; if (self.isIgnoreEvent){ return; }else if (self.timeInterval > 0){ [self performSelector:@selector(resetState) withObject:nil afterDelay:self.timeInterval]; } } //此處 methodA和methodB方法IMP互換了,實際上執行 sendAction;因此不會死循環 self.isIgnoreEvent = YES; [self sure_SendAction:action to:target forEvent:event]; } //runtime 動態綁定 屬性 - (void)setIsIgnoreEvent:(BOOL)isIgnoreEvent{ // 注意BOOL類型 須要用OBJC_ASSOCIATION_RETAIN_NONATOMIC 不要用錯,不然set方法會賦值出錯 objc_setAssociatedObject(self, @selector(isIgnoreEvent), @(isIgnoreEvent), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (BOOL)isIgnoreEvent{ //_cmd == @select(isIgnore); 和set方法裏一致 return [objc_getAssociatedObject(self, _cmd) boolValue]; } - (void)setIsIgnore:(BOOL)isIgnore{ // 注意BOOL類型 須要用OBJC_ASSOCIATION_RETAIN_NONATOMIC 不要用錯,不然set方法會賦值出錯 objc_setAssociatedObject(self, @selector(isIgnore), @(isIgnore), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (BOOL)isIgnore{ //_cmd == @select(isIgnore); 和set方法裏一致 return [objc_getAssociatedObject(self, _cmd) boolValue]; } - (void)resetState{ [self setIsIgnoreEvent:NO]; } @end
實例四:全局更換控件初始效果
以UILabel爲例,在項目比較成熟的基礎上,應用中須要引入新的字體,須要更換全部Label的默認字體,可是同時,對於一些特殊設置了字體的label又不須要更換。乍看起來,這個問題確實十分棘手,首先項目比較大,一個一個設置全部使用到的label的font工做量是巨大的,而且在許多動態展現的界面中,可能會漏掉一些label,產生bug。其次,項目中的label來源並不惟一,有用代碼建立的,有xib和storyBoard中的,這也將浪費很大的精力。這時Method Swizzling能夠解決此問題,避免繁瑣的操做。
#import "UILabel+Swizzling.h" #import "NSObject+Swizzling.h" @implementation UILabel (Swizzling) + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [self methodSwizzlingWithOriginalSelector:@selector(init) bySwizzledSelector:@selector(sure_Init)]; [self methodSwizzlingWithOriginalSelector:@selector(initWithFrame:) bySwizzledSelector:@selector(sure_InitWithFrame:)]; [self methodSwizzlingWithOriginalSelector:@selector(awakeFromNib) bySwizzledSelector:@selector(sure_AwakeFromNib)]; }); } - (instancetype)sure_Init{ id __self = [self sure_Init]; UIFont * font = [UIFont fontWithName:@"Zapfino" size:self.font.pointSize]; if (font) { self.font=font; } return __self; } - (instancetype)sure_InitWithFrame:(CGRect)rect{ id __self = [self sure_InitWithFrame:rect]; UIFont * font = [UIFont fontWithName:@"Zapfino" size:self.font.pointSize]; if (font) { self.font=font; } return __self; } - (void)sure_AwakeFromNib{ [self sure_AwakeFromNib]; UIFont * font = [UIFont fontWithName:@"Zapfino" size:self.font.pointSize]; if (font) { self.font=font; } } @end
這一實例我的認爲使用率可能不高,對於產品的設計這些點都是已經肯定好的,更改的概率很低。何況咱們也可使用appearance來進行統一設置。
實例五:App熱修復
由於AppStore上線審覈時間較長,且若是在線上版本出現bug修復起來也是很困難,這時App熱修復就能夠解決此問題。熱修復即在不更改線上版本的前提下,對線上版本進行更新甚至添加模塊。國內比較好的熱修復技術:JSPatch。JSPatch能作到經過JS調用和改寫OC方法最根本的緣由是Objective-C是動態語言,OC上全部方法的調用/類的生成都經過Objective-C Runtime在運行時進行,咱們能夠經過類名/方法名反射獲得相應的類和方法,進而替換出現bug的方法或者添加方法等。bang的博客上有詳細的描述有興趣能夠參考,這裏就不贅述了。
實例六:App異常加載佔位圖通用類封裝(更新於:2016/12/01)
詳情可見文章:《零行代碼爲App添加異常加載佔位圖》
在該功能模塊中,使用Runtime Method Swizzling進行替換tableView、collectionView的reloadData方法,使得每當執行刷新操做時,自動檢測當前組數與行數,從而實現零代碼判斷佔位圖是否顯示的功能,一樣也適用於網絡異常等狀況,詳細設置可前往閱讀。
實例七:全局修改導航欄後退(返回)按鈕(更新於:2016/12/05)
在真實項目開發中,會全局統一某控件樣式,以導航欄後退(返回)按鈕爲例,一般項目中會固定爲返回字樣,或者以圖片進行顯示等。
iOS默認的返回按鈕樣式以下,默認爲藍色左箭頭,文字爲上一界面標題文字。
默認返回按鈕樣式
這裏咱們仍能夠經過Runtime Method Swizzling來實現該需求,在使用Method Swizzling進行更改以前,必須考慮注意事項,即儘量的不影響原有操做,好比對於系統默認的返回按鈕,與其對應的是有界面邊緣右滑返回功能的,所以咱們進行統一更改後不可以使其功能廢棄。
閒話少說,咱們建立基於UINavigationItem
的類別,在其load
方法中替換方法backBarButtonItem
代碼以下
#import "UINavigationItem+Swizzling.h" #import "NSObject+Swizzling.h" static char *kCustomBackButtonKey; @implementation UINavigationItem (Swizzling) + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [self methodSwizzlingWithOriginalSelector:@selector(backBarButtonItem) bySwizzledSelector:@selector(sure_backBarButtonItem)]; }); } - (UIBarButtonItem*)sure_backBarButtonItem { UIBarButtonItem *backItem = [self sure_backBarButtonItem]; if (backItem) { return backItem; } backItem = objc_getAssociatedObject(self, &kCustomBackButtonKey); if (!backItem) { backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:NULL]; objc_setAssociatedObject(self, &kCustomBackButtonKey, backItem, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } return backItem; } @end
這裏進行將返回按鈕的文字清空操做,其餘需求樣式你們也可隨意替換,如今再次運行程序,就會發現全部的返回按鈕均只剩左箭頭,並右滑手勢依然有效。如圖所示
全局統一設置返回按鈕
文/賣報的小畫家Sure(簡書做者) 原文連接:http://www.jianshu.com/p/f6dad8e1b848