method-swizzling 是什么?
method-swizzling
的含義是方法交換
,其主要作用是在運行時將一個方法的實現替換成另一個方法的實現
,這就是我們常說的iOS黑魔法
,-
在OC中就是
利用method-swizzling實現AOP
,其中AOP
(Aspect Oriented Programming,面向切面編程)是一種編程的思想,區別于OOP(面向對象編程)
- OOP和AOP都是一種編程的思想
-
OOP
編程思想更加傾向于對業務模塊的封裝
,劃分出更加清晰的邏輯單元; - 而
AOP
是面向切面進行提取封裝,提取各個模塊中的公共部分,提高模塊的復用率,降低業務之間的耦合性
。
每個類都維護著一個
方法列表
,即methodList
,methodList
中有不同的方法
即Method
,每個方法中包含了方法的sel
和IMP
,方法交換就是將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不一定指向aIMPmethod_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
方法時崩潰,下面來進行詳細說明
[s personInstanceMethod];
中不報錯是因為student
中的imp
交換成了lg_studentInstanceMethod
,而LGStudent
中有這個方法(在LG分類中),所以不會報錯崩潰的點在于
[p personInstanceMethod];
,其本質原因:LGStudent
的分類LG
中進行了方法交換
,將person
中imp
交換成了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_replaceMethod
、class_addMethod
和method_exchangeImplementations
的源碼實現
其中class_replaceMethod
和class_addMethod
中都調用了addMethod
方法,區別在于bool值的判斷,下面是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];
}
經過調試,發現運行代碼會崩潰,報錯結果如下所示
原因是 棧溢出
,遞歸死循環
了,那么為什么會發生遞歸呢?----主要是因為 personInstanceMethod
沒有實現,然后在方法交換時,始終都找不到oriMethod,然后交換了寂寞,即交換失敗,當我們調用personInstanceMethod(oriMethod)
時,也就是oriMethod
會進入LG中lg_studentInstanceMethod
方法,然后這個方法中又調用了lg_studentInstanceMethod
,此時的lg_studentInstanceMethod
并沒有指向oriMethod
,然后導致了自己調自己
,即遞歸死循環
優化:避免遞歸死循環
- 如果
oriMethod
為空,為了避免方法交換沒有意義,而被廢棄,需要做一些事情通過
class_addMethod
給oriSEL
添加swiMethod
方法通過
method_setImplementation
將swiMethod
的IMP
指向不做任何事的空實現
+ (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_addMethod
和class_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中NSNumber
、NSArray
、NSDictionary
等這些類都是類簇,一個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];
-
打印結果如下,會輸出崩潰的日志,但是實際并不會崩潰
數組越界調試-不會崩潰