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

iOS 底層原理 文章匯總

method-swizzling 是什么?

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

  • 在OC中就是利用method-swizzling實現(xiàn)AOP,其中AOP(Aspect Oriented Programming,面向切面編程)是一種編程的思想,區(qū)別于OOP(面向?qū)ο缶幊蹋?/code>

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

如下圖所示,交換前后的sel和IMP的對應(yīng)關(guān)系


方法交換原理

method-swizzling涉及的相關(guān)API

  • 通過sel獲取方法Method

    • class_getInstanceMethod:獲取實例方法

    • class_getClassMethod:獲取類方法

  • method_getImplementation:獲取一個方法的實現(xiàn)

  • method_setImplementation:設(shè)置一個方法的實現(xiàn)

  • method_getTypeEncoding:獲取方法實現(xiàn)的編碼類型

  • class_addMethod:添加方法實現(xiàn)

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

  • method_exchangeImplementations:交換兩個方法的實現(xiàn),即 aIMP -> bIMP, bIMP -> aIMP

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

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

解決方案

可以通過單例設(shè)計原則,使方法交換只執(zhí)行一次,在OC中可以通過dispatch_once實現(xiàn)單例

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

坑點2:子類沒有實現(xiàn),父類實現(xiàn)了

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

//*********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

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

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

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

@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{
    ////是否會產(chǎn)生遞歸?--不會產(chǎn)生遞歸,原因是lg_studentInstanceMethod 會走 oriIMP,即personInstanceMethod的實現(xiàn)中去
    [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);
}

通過實際代碼的調(diào)試,發(fā)現(xiàn)會在p調(diào)用personInstanceMethod方法時崩潰,下面來進行詳細說明

坑點2-崩潰日志

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

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

優(yōu)化:避免imp找不到

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

  • 如果添加成功,即類中沒有這個方法,則通過class_replaceMethod進行替換,其內(nèi)部會調(diào)用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);
   
    // 一般交換方法: 交換自己有的方法 -- 走下面 因為自己有意味添加方法失敗
    // 交換自己沒有實現(xiàn)的方法:
    //   首先第一步:會先嘗試給自己添加要交換的方法 :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的源碼實現(xiàn)

源碼實現(xiàn)

其中class_replaceMethodclass_addMethod中都調(diào)用了addMethod方法,區(qū)別在于bool值的判斷,下面是addMethod的源碼實現(xiàn)

addMethod源碼實現(xiàn)

坑點3:子類沒有實現(xiàn),父類也沒有實現(xiàn),下面的調(diào)用有什么問題?

在調(diào)用personInstanceMethod方法時,父類LGPerson中只有聲明,沒有實現(xiàn),子類LGStudent中既沒有聲明,也沒有實現(xiàn)

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

@implementation LGPerson
@end

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

@implementation LGStudent
@end

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

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

經(jīng)過調(diào)試,發(fā)現(xiàn)運行代碼會崩潰,報錯結(jié)果如下所示


坑點3-崩潰

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

優(yōu)化:避免遞歸死循環(huán)

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

    • 通過method_setImplementationswiMethodIMP指向不做任何事的空實現(xiàn)

+ (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復(fù)制一個不做任何事的空實現(xiàn),代碼如下:
        class_addMethod(cls, oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
        method_setImplementation(swiMethod, imp_implementationWithBlock(^(id self, SEL _cmd){ }));
    }
    
    // 一般交換方法: 交換自己有的方法 -- 走下面 因為自己有意味添加方法失敗
    // 交換自己沒有實現(xiàn)的方法:
    //   首先第一步:會先嘗試給自己添加要交換的方法 :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的原理是類似的,唯一的區(qū)別是類方法存在元類中,所以可以做如下操作

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

@implementation LGStudent

@end
  • 在LGStudent的分類的load方法中實現(xiàn)類方法的方法交換
+ (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方法獲取類方法

    • 在調(diào)用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復(fù)制一個不做任何事的空實現(xiàn),代碼如下:
        class_addMethod(object_getClass(cls), oriSEL, method_getImplementation(swiMethod), method_getTypeEncoding(swiMethod));
        method_setImplementation(swiMethod, imp_implementationWithBlock(^(id self, SEL _cmd){
            NSLog(@"來了一個空的 imp");
        }));
    }
    
    // 一般交換方法: 交換自己有的方法 -- 走下面 因為自己有意味添加方法失敗
    // 交換自己沒有實現(xiàn)的方法:
    //   首先第一步:會先嘗試給自己添加要交換的方法 :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);
    }
    
}
  • 調(diào)用如下
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [LGStudent sayHello];
}
  • 運行結(jié)果如下,由于符合方法沒有實現(xiàn),所以會走到空的imp
    坑點3-優(yōu)化調(diào)試結(jié)果

method-swizzling的應(yīng)用

method-swizzling最常用的應(yīng)用是防止數(shù)組、字典等越界崩潰

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

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

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

以 NSArray 為例

  • 創(chuàng)建NSArray的一個分類CJLArray
@implementation NSArray (CJLArray)
//如果下面代碼不起作用,造成這個問題的原因大多都是其調(diào)用了super load方法。在下面的load方法中,不應(yīng)該調(diào)用父類的load方法。這樣會導(dǎo)致方法交換無效
+ (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);
}

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

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


    數(shù)組越界調(diào)試-不會崩潰
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容