iOS-底層原理 21:Method-Swizzling 方法交換

iOS 底層原理 文章匯總

method-swizzling 是什么?

  • method-swizzling的含義是方法交換,其主要作用是在運行時將一個方法的實現替換成另一個方法的實現,這就是我們常說的iOS黑魔法

  • 在OC中就是利用method-swizzling實現AOP,其中AOP(Aspect Oriented Programming,面向切面編程)是一種編程的思想,區別于OOP(面向對象編程)

    • OOP和AOP都是一種編程的思想
    • OOP編程思想更加傾向于對業務模塊的封裝,劃分出更加清晰的邏輯單元;
    • AOP面向切面進行提取封裝,提取各個模塊中的公共部分,提高模塊的復用率,降低業務之間的耦合性
  • 每個類都維護著一個方法列表,即methodListmethodList中有不同的方法Method,每個方法中包含了方法的selIMP,方法交換就是將sel和imp原本的對應斷開,并將sel和新的IMP生成對應關系

如下圖所示,交換前后的sel和IMP的對應關系


方法交換原理

method-swizzling涉及的相關API

  • 通過sel獲取方法Method

    • class_getInstanceMethod:獲取實例方法

    • class_getClassMethod:獲取類方法

  • method_getImplementation:獲取一個方法的實現

  • method_setImplementation:設置一個方法的實現

  • method_getTypeEncoding:獲取方法實現的編碼類型

  • class_addMethod:添加方法實現

  • class_replaceMethod:用一個方法的實現,替換另一個方法的實現,即aIMP 指向 bIMP,但是bIMP不一定指向aIMP

  • method_exchangeImplementations:交換兩個方法的實現,即 aIMP -> bIMP, bIMP -> aIMP

坑點1:method-swizzling使用過程中的一次性問題

所謂的一次性就是:mehod-swizzling寫在load方法中,而load方法會主動調用多次,這樣會導致方法的重復交換,使方法sel的指向又恢復成原來的imp的問題

解決方案

可以通過單例設計原則,使方法交換只執行一次,在OC中可以通過dispatch_once實現單例

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [LGRuntimeTool lg_bestMethodSwizzlingWithClass:self oriSEL:@selector(helloword) swizzledSEL:@selector(lg_studentInstanceMethod)];
    });
}

坑點2:子類沒有實現,父類實現了

在下面這段代碼中,LGPerson中實現了personInstanceMethod,而LGStudent繼承自LGPerson,沒有實現personInstanceMethod,運行下面這段代碼會出現什么問題?

//*********LGPerson類*********
@interface LGPerson : NSObject
- (void)personInstanceMethod;
@end

@implementation LGPerson
- (void)personInstanceMethod{
    NSLog(@"person對象方法:%s",__func__);  
}
@end

//*********LGStudent類*********
@interface LGStudent : LGPerson
- (void)helloword;
+ (void)sayHello;
@end

@implementation LGStudent
@end

//*********調用*********
- (void)viewDidLoad {
    [super viewDidLoad];

    // 黑魔法坑點二: 子類沒有實現 - 父類實現
    LGStudent *s = [[LGStudent alloc] init];
    [s personInstanceMethod];
    
    LGPerson *p = [[LGPerson alloc] init];
    [p personInstanceMethod];
}

其中,方法交換代碼如下,是通過LGStudent的分類LG實現

@implementation LGStudent (LG)

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [LGRuntimeTool lg_methodSwizzlingWithClass:self oriSEL:@selector(personInstanceMethod) swizzledSEL:@selector(lg_studentInstanceMethod)];
    });
}

// personInstanceMethod 我需要父類的這個方法的一些東西
// 給你加一個personInstanceMethod 方法
// imp

- (void)lg_studentInstanceMethod{
    ////是否會產生遞歸?--不會產生遞歸,原因是lg_studentInstanceMethod 會走 oriIMP,即personInstanceMethod的實現中去
    [self lg_studentInstanceMethod];
    NSLog(@"LGStudent分類添加的lg對象方法:%s",__func__);
}

@end

下面是封裝好的method-swizzling方法

@implementation LGRuntimeTool
+ (void)lg_methodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL{
    
    if (!cls) NSLog(@"傳入的交換類不能為空");

    Method oriMethod = class_getInstanceMethod(cls, oriSEL);
    Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);
    method_exchangeImplementations(oriMethod, swiMethod);
}

通過實際代碼的調試,發現會在p調用personInstanceMethod方法時崩潰,下面來進行詳細說明

坑點2-崩潰日志

  • [s personInstanceMethod];中不報錯是因為 student中的imp交換成了lg_studentInstanceMethod,而LGStudent中有這個方法(在LG分類中),所以不會報錯

  • 崩潰的點在于[p personInstanceMethod];,其本質原因:LGStudent的分類LG中進行了方法交換,將personimp 交換成了 LGStudent中的lg_studentInstanceMethod,然后需要去 LGPerson中的找lg_studentInstanceMethod,但是LGPerson中沒有lg_studentInstanceMethod方法,即相關的imp找不到,所以就崩潰了

優化:避免imp找不到

通過class_addMethod嘗試添加你要交換的方法

  • 如果添加成功,即類中沒有這個方法,則通過class_replaceMethod進行替換,其內部會調用class_addMethod進行添加
  • 如果添加不成功,即類中有這個方法,則通過method_exchangeImplementations進行交換
+ (void)lg_betterMethodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL{
    
    if (!cls) NSLog(@"傳入的交換類不能為空");
    
    Method oriMethod = class_getInstanceMethod(cls, oriSEL);
    Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);
   
    // 一般交換方法: 交換自己有的方法 -- 走下面 因為自己有意味添加方法失敗
    // 交換自己沒有實現的方法:
    //   首先第一步:會先嘗試給自己添加要交換的方法 :personInstanceMethod (SEL) -> swiMethod(IMP)
    //   然后再將父類的IMP給swizzle  personInstanceMethod(imp) -> swizzledSEL 

    BOOL success = class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(oriMethod));

    if (success) {// 自己沒有 - 交換 - 沒有父類進行處理 (重寫一個)
        class_replaceMethod(cls, swizzledSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
    }else{ // 自己有
        method_exchangeImplementations(oriMethod, swiMethod);
    }   
}

下面是class_replaceMethodclass_addMethodmethod_exchangeImplementations的源碼實現

源碼實現

其中class_replaceMethodclass_addMethod中都調用了addMethod方法,區別在于bool值的判斷,下面是addMethod的源碼實現

addMethod源碼實現

坑點3:子類沒有實現,父類也沒有實現,下面的調用有什么問題?

在調用personInstanceMethod方法時,父類LGPerson中只有聲明,沒有實現,子類LGStudent中既沒有聲明,也沒有實現

//*********LGPerson類*********
@interface LGPerson : NSObject
- (void)personInstanceMethod;
@end

@implementation LGPerson
@end

//*********LGStudent類*********
@interface LGStudent : LGPerson
- (void)helloword;
+ (void)sayHello;
@end

@implementation LGStudent
@end

//*********調用*********
- (void)viewDidLoad {
    [super viewDidLoad];

    // 黑魔法坑點二: 子類沒有實現 - 父類實現
    LGStudent *s = [[LGStudent alloc] init];
    [s personInstanceMethod];
    
    LGPerson *p = [[LGPerson alloc] init];
    [p personInstanceMethod];
}

經過調試,發現運行代碼會崩潰,報錯結果如下所示


坑點3-崩潰

原因是 棧溢出遞歸死循環了,那么為什么會發生遞歸呢?----主要是因為 personInstanceMethod沒有實現,然后在方法交換時,始終都找不到oriMethod,然后交換了寂寞,即交換失敗,當我們調用personInstanceMethod(oriMethod)時,也就是oriMethod會進入LG中lg_studentInstanceMethod方法,然后這個方法中又調用了lg_studentInstanceMethod,此時的lg_studentInstanceMethod并沒有指向oriMethod ,然后導致了自己調自己,即遞歸死循環

優化:避免遞歸死循環

  • 如果oriMethod為空,為了避免方法交換沒有意義,而被廢棄,需要做一些事情
    • 通過class_addMethodoriSEL添加swiMethod方法

    • 通過method_setImplementationswiMethodIMP指向不做任何事的空實現

+ (void)lg_bestMethodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL{
    
    if (!cls) NSLog(@"傳入的交換類不能為空");
    
    Method oriMethod = class_getInstanceMethod(cls, oriSEL);
    Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);
    
    if (!oriMethod) {
        // 在oriMethod為nil時,替換后將swizzledSEL復制一個不做任何事的空實現,代碼如下:
        class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
        method_setImplementation(swiMethod, imp_implementationWithBlock(^(id self, SEL _cmd){ }));
    }
    
    // 一般交換方法: 交換自己有的方法 -- 走下面 因為自己有意味添加方法失敗
    // 交換自己沒有實現的方法:
    //   首先第一步:會先嘗試給自己添加要交換的方法 :personInstanceMethod (SEL) -> swiMethod(IMP)
    //   然后再將父類的IMP給swizzle  personInstanceMethod(imp) -> swizzledSEL
    //oriSEL:personInstanceMethod

    BOOL didAddMethod = class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
    if (didAddMethod) {
        class_replaceMethod(cls, swizzledSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
    }else{
        method_exchangeImplementations(oriMethod, swiMethod);
    }
    
}

method-swizzling - 類方法

類方法和實例方法的method-swizzling的原理是類似的,唯一的區別是類方法存在元類中,所以可以做如下操作

  • LGStudent中只有類方法sayHello的聲明,沒有實現
@interface LGStudent : LGPerson
- (void)helloword;
+ (void)sayHello;
@end

@implementation LGStudent

@end
  • 在LGStudent的分類的load方法中實現類方法的方法交換
+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
         [LGRuntimeTool lg_bestClassMethodSwizzlingWithClass:self oriSEL:@selector(sayHello) swizzledSEL:@selector(lg_studentClassMethod)];
    });
}
+ (void)lg_studentClassMethod{
    NSLog(@"LGStudent分類添加的lg類方法:%s",__func__);
   [[self class] lg_studentClassMethod];
}
  • 封裝的類方法的方法交換如下
    • 需要通過class_getClassMethod方法獲取類方法

    • 在調用class_addMethodclass_replaceMethod方法添加和替換時,需要傳入的類是元類,元類可以通過object_getClass方法獲取類的元類

//封裝的method-swizzling方法
+ (void)lg_bestClassMethodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL{
    
    if (!cls) NSLog(@"傳入的交換類不能為空");

    Method oriMethod = class_getClassMethod([cls class], oriSEL);
    Method swiMethod = class_getClassMethod([cls class], swizzledSEL);
    
    if (!oriMethod) { // 避免動作沒有意義
        // 在oriMethod為nil時,替換后將swizzledSEL復制一個不做任何事的空實現,代碼如下:
        class_addMethod(object_getClass(cls), oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
        method_setImplementation(swiMethod, imp_implementationWithBlock(^(id self, SEL _cmd){
            NSLog(@"來了一個空的 imp");
        }));
    }
    
    // 一般交換方法: 交換自己有的方法 -- 走下面 因為自己有意味添加方法失敗
    // 交換自己沒有實現的方法:
    //   首先第一步:會先嘗試給自己添加要交換的方法 :personInstanceMethod (SEL) -> swiMethod(IMP)
    //   然后再將父類的IMP給swizzle  personInstanceMethod(imp) -> swizzledSEL
    //oriSEL:personInstanceMethod

    BOOL didAddMethod = class_addMethod(object_getClass(cls), oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
    
    if (didAddMethod) {
        class_replaceMethod(object_getClass(cls), swizzledSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
    }else{
        method_exchangeImplementations(oriMethod, swiMethod);
    }
    
}
  • 調用如下
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [LGStudent sayHello];
}
  • 運行結果如下,由于符合方法沒有實現,所以會走到空的imp
    坑點3-優化調試結果

method-swizzling的應用

method-swizzling最常用的應用是防止數組、字典等越界崩潰

在iOS中NSNumberNSArrayNSDictionary等這些類都是類簇,一個NSArray的實現可能由多個類組成。所以如果想對NSArray進行Swizzling,必須獲取到其“真身”進行Swizzling,直接對NSArray進行操作是無效的

下面列舉了NSArray和NSDictionary本類的類名,可以通過Runtime函數取出本類。

類名 真身
NSArray __NSArrayI
NSMutableArray __NSArrayM
NSDictionary __NSDictionaryI
NSMutableDictionary __NSDictionaryM

以 NSArray 為例

  • 創建NSArray的一個分類CJLArray
@implementation NSArray (CJLArray)
//如果下面代碼不起作用,造成這個問題的原因大多都是其調用了super load方法。在下面的load方法中,不應該調用父類的load方法。這樣會導致方法交換無效
+ (void)load{
    Method fromMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
    Method toMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(cjl_objectAtIndex:));
    
    method_exchangeImplementations(fromMethod, toMethod);
}

//如果下面代碼不起作用,造成這個問題的原因大多都是其調用了super load方法。在下面的load方法中,不應該調用父類的load方法。這樣會導致方法交換無效
- (id)cjl_objectAtIndex:(NSUInteger)index{
    //判斷下標是否越界,如果越界就進入異常攔截
    if (self.count-1 < index) {
        // 這里做一下異常處理,不然都不知道出錯了。
#ifdef DEBUG  // 調試階段
        return [self cjl_objectAtIndex:index];
#else // 發布階段
        @try {
            return [self cjl_objectAtIndex:index];
        } @catch (NSException *exception) {
            // 在崩潰后會打印崩潰信息,方便我們調試。
            NSLog(@"---------- %s Crash Because Method %s  ----------\n", class_getName(self.class), __func__);
            NSLog(@"%@", [exception callStackSymbols]);
            return nil;
        } @finally {
            
        }
#endif
    }else{ // 如果沒有問題,則正常進行方法調用
        return [self cjl_objectAtIndex:index];
    }
}

@end
  • 測試代碼
 NSArray *array = @[@"1", @"2", @"3"];
[array objectAtIndex:3];
  • 打印結果如下,會輸出崩潰的日志,但是實際并不會崩潰


    數組越界調試-不會崩潰
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,797評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,179評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,628評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,642評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,444評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,948評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,040評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,185評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,717評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,602評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,794評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,316評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,045評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,418評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,671評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,414評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,750評論 2 370

推薦閱讀更多精彩內容