method-swizzling 是什么?
method-swizzling的含義是方法交換,其主要作用是在運(yùn)行時將一個方法的實現(xiàn)替換成另一個方法的實現(xiàn),這就是我們常說的iOS黑魔法,
在OC中就是利用method-swizzling實現(xiàn)AOP,其中AOP(Aspect Oriented Programming,面向切面編程)是一種編程的思想,區(qū)別于OOP(面向?qū)ο缶幊蹋?/code>
OOP和AOP都是一種編程的思想ios_lowLevel
-
OOP編程思想更加傾向于對業(yè)務(wù)模塊的封裝,劃分出更加清晰的邏輯單元; -
AOP是面向切面進(jìn)行提取封裝,提取各個模塊中的公共部分,提高模塊的復(fù)用率,降低業(yè)務(wù)之間的耦合性。
每個類都維護(hù)著一個方法列表,即methodList,methodList中有不同的方法即Method,每個方法中包含了方法的sel和IMP,方法交換就是將sel和imp原本的對應(yīng)斷開,并將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), 子類進(jìn)行方法交換
在下面這段代碼中,LGPerson中實現(xiàn)了personInstanceMethod,而LGStudent繼承自LGPerson,沒有實現(xiàn)personInstanceMethod,運(yùn)行下面這段代碼會出現(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方法時崩潰,下面來進(jìn)行詳細(xì)說明
坑點2-崩潰日志
[s personInstanceMethod];中不報錯是因為 student中的imp交換成了lg_studentInstanceMethod,而LGStudent中有這個方法(在LG分類中),所以不會報錯
崩潰的點在于[p personInstanceMethod];,其本質(zhì)原因:LGStudent的分類LG中進(jìn)行了方法交換,將person中imp 交換成了 LGStudent中的lg_studentInstanceMethod,然后需要去LGPerson中的找lg_studentInstanceMethod,但是LGPerson中沒有l(wèi)g_studentInstanceMethod方法,即相關(guān)的imp找不到,所以就崩潰了
解決方案:避免imp找不到
-
通過
class_addMethod嘗試添加你要交換的方法- 如果
添加成功,即類中沒有這個方法,則通過class_replaceMethod進(jìn)行替換,其內(nèi)部會調(diào)用class_addMethod進(jìn)行添加 - 如果添加
不成功,即類中有這個方法,則通過method_exchangeImplementations進(jìn)行交換
- 如果
+ (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) {// 自己沒有 - 交換 - 沒有父類進(jìn)行處理 (重寫一個)
class_replaceMethod(cls, swizzledSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));
}else{ // 自己有
method_exchangeImplementations(oriMethod, swiMethod);
}
}
下面是class_addMethod、class_replaceMethod、和method_exchangeImplementations的源碼實現(xiàn)
class_addMethod 內(nèi)是調(diào)用addMethod
BOOL
class_addMethod(Class cls, SEL name, IMP imp, const char *types)
{
if (!cls) return NO;
mutex_locker_t lock(runtimeLock);
return ! addMethod(cls, name, imp, types ?: "", NO);
}
class_replaceMethod 內(nèi)部也是調(diào)用的是 addMethod
IMP
class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
{
if (!cls) return nil;
mutex_locker_t lock(runtimeLock);
return addMethod(cls, name, imp, types ?: "", YES);
}
method_exchangeImplementations 則是交換Method的imp
void method_exchangeImplementations(Method m1, Method m2)
{
if (!m1 || !m2) return;
mutex_locker_t lock(runtimeLock);
IMP m1_imp = m1->imp;
m1->imp = m2->imp;
m2->imp = m1_imp;
// RR/AWZ updates are slow because class is unknown
// Cache updates are slow because class is unknown
// fixme build list of classes whose Methods are known externally?
flushCaches(nil);
adjustCustomFlagsForMethodChange(nil, m1);
adjustCustomFlagsForMethodChange(nil, m2);
}

再看addMethod內(nèi)部實現(xiàn)

其實上面優(yōu)化也不行, 只判斷了初始方法是否實現(xiàn)就會出現(xiàn)下面一種情況
坑點3:父類未實現(xiàn), 子類實現(xiàn)了, 子類進(jìn)行方法交換, 也就是swizzledSEL未實現(xiàn),或者子類沒有實現(xiàn),父類也沒有實現(xiàn),下面的調(diào)用有什么問題?

原因是 棧溢出,遞歸死循環(huán)了,那么為什么會發(fā)生遞歸呢?----主要是因為personInstanceMethod沒有實現(xiàn),然后在方法交換時,始終都找不到oriMethod,然后交換了寂寞,即交換失敗,當(dāng)我們調(diào)用personInstanceMethod(oriMethod)時,也就是oriMethod會進(jìn)入LG中lg_studentInstanceMethod方法,然后這個方法中又調(diào)用了lg_studentInstanceMethod,此時的lg_studentInstanceMethod并沒有指向oriMethod` ,然后導(dǎo)致了自己調(diào)自己,即遞歸死循環(huán)
優(yōu)化:避免遞歸死循環(huán)
如果oriMethod為空,為了避免方法交換沒有意義,而被廢棄,需要做一些事情
通過class_addMethod給oriSEL添加swiMethod方法
通過method_setImplementation將swiMethod的IMP指向不做任何事的空實現(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_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復(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];
}
運(yùn)行結(jié)果如下,由于符合方法沒有實現(xiàn),所以會走到空的imp中

method-swizzling的應(yīng)用
method-swizzling最常用的應(yīng)用是防止數(shù)組、字典等越界崩潰
在iOS中NSNumber、NSArray、NSDictionary等這些類都是類簇,一個NSArray的實現(xiàn)可能由多個類組成。所以如果想對NSArray進(jìn)行Swizzling,必須獲取到其“真身”進(jìn)行Swizzling,直接對NSArray進(jìn)行操作是無效的。
下面列舉了NSArray和NSDictionary本類的類名,可以通過Runtime函數(shù)取出本類。

以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{
//判斷下標(biāo)是否越界,如果越界就進(jìn)入異常攔截
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{ // 如果沒有問題,則正常進(jìn)行方法調(diào)用
return [self cjl_objectAtIndex:index];
}
}
@end
測試代碼
NSArray *array = @[@"1", @"2", @"3"];
[array objectAtIndex:3];
打印結(jié)果如下,會輸出崩潰的日志,但是實際并不會崩潰
