Method Swizzling 原理
Method Swizzling 是 Objective-C runtime 的一個體現,他可以動態的添加及替換類的方法。首先,我們來看下 Objective-C Method 的數據結構:
typedef struct method_t *Method;
struct method_t {
SEL name;
const char *types;
IMP imp;
struct SortBySELAddress :
public std::binary_function<const method_t&,
const method_t&, bool>
{
bool operator() (const method_t& lhs,
const method_t& rhs)
{ return lhs.name < rhs.name; }
};
};
其實,他就是 struct method_t 類型的一個指針,在此結構體中定義了三個成員變量及一個函數方法:
- name:表示方法的名稱,唯一的標識,方法名只能唯一;
- types:標識方法的參數和返回值類型;
- imp:一個函數指針,指向是方法的實現;
- SortBySELAddress: 從方法名就可以看出,根據方法名的地址的一個排序函數。
Method Swizzling 有什么用
Method Swizzling 可以對 Objective-C 的函數方法進行hook,近而達到埋點,添加方法功能等特性。
Method Sizzling 實踐
- 添加
@implementation UIView (DTUIView)
+ (void)load{
// 實現init 與 dt_addSubview方法的交換
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL org_Selector = @selector(addSubview:);
SEL dt_Selector = @selector(dt_addSubview:);
Method org_method = class_getInstanceMethod([self class], org_Selector);
Method dt_method = class_getInstanceMethod([self class], dt_Selector);
BOOL isAdd = class_addMethod(self, org_Selector, method_getImplementation(dt_method), method_getTypeEncoding(dt_method));
if (isAdd) {
class_replaceMethod(self, dt_Selector, method_getImplementation(org_method), method_getTypeEncoding(org_method));
}else{
method_exchangeImplementations(org_method, dt_method);
}
});
}
- (void)dt_addSubview:(UIView *)view{
[self dt_addSubview:view];
// do some thing
}
- 通過 Category 的 +(void)load 方法中添加代碼,且 load 方法是按照父類--子類--分類的調用順序調用的,且 laod 方法不會被子類的方法所覆蓋掉;
- 主要 swizzling 代碼卸載 dispatch_once_t 方法中,防止被多次調用,保證線程安全;
- 先用 class_addMethod 嘗試在類方法中添加要操作的方法,然后判斷是否類中添加時候成功(類中原先有無操作方法)。添加成功(無操作方法),然后交換函數的實現 imp ;如果添加失敗(有該操作方法),直接交換方法實現即可。
- 注意一點在 dt_init 實現里面調用的還是 dt_init,因為 dt_init 實現已被替換,實質被實現的是 init
2.刪除
既然我們使用它來 swizzling 方法,那么我們在 swizzling 完后某一時間我們不需要了,要回到原來的實現,這時候我們該怎么做呢?平常可以加個開關來決定是否操作,但是隨著代碼的累加,業務的增多。這將會變得很亂,管理很難。所以我們必須想到一個好的辦法來解決。辦法就是通過 runtime 的一個函數 class_copyMethodList ,來遍歷出他所有的 Method,我們之前說過一個 Method 就是一個結構體指針,所以內部參數 Imp 和 Method 一一對應的, 我們只需在 swizzling 的時候保存下 Imp,就可以遍歷 Method swizzling 回來。
// 在 swizzling 的過程中記錄 swizzling 的 Imp
static IMP org_imp = NULL;
static IMP dt_imp = NULL;
org_imp = method_getImplementation(org_method);
dt_imp = method_getImplementation(dt_method);
+ (void)restore{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (!org_imp || !dt_imp) return;
Method org_method = NULL;
Method dt_method = NULL;
unsigned int outCount = 0;
Method *methodList = class_copyMethodList(self, &outCount);
for (unsigned int idx = 0; idx < outCount; idx ++) {
Method method = methodList[idx];
IMP imp = method_getImplementation(method);
if (imp == org_imp) {
org_method = method;
}
else if (imp == dt_imp) {
dt_method = method;
}
}
if (org_method && dt_method) {
method_exchangeImplementations(org_method, dt_method);
}
else if (org_method) {
method_setImplementation(org_method, org_imp);
}
else if (dt_method) {
method_setImplementation(dt_method, dt_imp);
}
//清除
org_imp = NULL;
dt_imp = NULL;
});
}
以上代碼就是恢復原來的實現的代碼:
1.) restore 改方法需手動調用才可以恢復;
2.)同樣使用 dispatch_once_t 方法,確保執行一次。
Method Sizzling 類簇使用
開發中常用的 NSString、NSArray、NSDictionary 其實都是類簇(一組隱藏在公共接口下的私有類),所以對類簇進行 swizzling 時要注意 class 為類簇管理下的那個私有類。例如在開發中常遇到 NSDictionary 用字面量創建時,當 key 或者 value 為 nil 時,程序會 crash。這里我們 swizzling 他的初始化方法將 key 或者 value 為 nil 的情況全部替換為 NSNull 的一個實例,這樣不但使程序更加健壯,并且方便了我們開發調試。
@implementation NSDictionary (DTNSDictionary)
+ (void)load{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [NSClassFromString(@"__NSPlaceholderDictionary") class];
SEL org_Selector = @selector(initWithObjects:forKeys:count:);
SEL dt_Selector = @selector(dt_initWithObjects:forKeys:count:);
Method org_method = class_getInstanceMethod(class, org_Selector);
Method dt_method = class_getInstanceMethod(class, dt_Selector);
BOOL isAdd = class_addMethod(class, org_Selector, method_getImplementation(dt_method), method_getTypeEncoding(dt_method));
if (isAdd) {
class_replaceMethod(class, dt_Selector, method_getImplementation(org_method), method_getTypeEncoding(org_method));
}else{
method_exchangeImplementations(org_method, dt_method);
}
});
}
- (instancetype)dt_initWithObjects:(const id [])objects forKeys:(const id<NSCopying> [])keys count:(NSUInteger)cnt {
id newObjects[cnt];
id newKeys[cnt];
NSUInteger j = 0;
for (NSUInteger i = 0; i < cnt; i++) {
id key = keys[i];
id obj = objects[i];
if (!obj) {
obj = [NSNull null];
}
if (!key) {
key = [NSNull null];
}
newKeys[j] = key;
newObjects[j] = obj;
j++;
}
return [self dt_initWithObjects:newObjects forKeys:newKeys count:j];
}
@end
以上代碼 swizzling 的是 NSDictionary 管理下的的一個私有類 __NSPlaceholderDictionary ,而方法為initWithObjects:forKeys:count:,
結語
雖然 swizzling 解決了我們一些難以解決的棘手問題,讓我們開發走上了一些捷徑,但是我們要嚴謹的對待使用,做到有設計的使用。畢竟在一些黑魔法被濫用后造成的糟糕的結果是無法估量的。