Objective-C Method Swizzling

Method Swizzling 原理
Method Swizzling 是 Objective-C runtime 的一個(gè)體現(xiàn),他可以動(dòng)態(tài)的添加及替換類的方法。首先,我們來看下 Objective-C Method 的數(shù)據(jù)結(jié)構(gòu):

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; }
    };
};

其實(shí),他就是 struct method_t 類型的一個(gè)指針,在此結(jié)構(gòu)體中定義了三個(gè)成員變量及一個(gè)函數(shù)方法:

  • name:表示方法的名稱,唯一的標(biāo)識,方法名只能唯一;
  • types:標(biāo)識方法的參數(shù)和返回值類型;
  • imp:一個(gè)函數(shù)指針,指向是方法的實(shí)現(xiàn);
  • SortBySELAddress: 從方法名就可以看出,根據(jù)方法名的地址的一個(gè)排序函數(shù)。

Method Swizzling 有什么用
Method Swizzling 可以對 Objective-C 的函數(shù)方法進(jìn)行hook,近而達(dá)到埋點(diǎn),添加方法功能等特性。

Method Sizzling 實(shí)踐

  1. 添加
@implementation UIView (DTUIView)

+ (void)load{
   
   // 實(shí)現(xiàn)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 方法是按照父類--子類--分類的調(diào)用順序調(diào)用的,且 laod 方法不會被子類的方法所覆蓋掉;
  • 主要 swizzling 代碼卸載 dispatch_once_t 方法中,防止被多次調(diào)用,保證線程安全;
  • 先用 class_addMethod 嘗試在類方法中添加要操作的方法,然后判斷是否類中添加時(shí)候成功(類中原先有無操作方法)。添加成功(無操作方法),然后交換函數(shù)的實(shí)現(xiàn) imp ;如果添加失敗(有該操作方法),直接交換方法實(shí)現(xiàn)即可。
  • 注意一點(diǎn)在 dt_init 實(shí)現(xiàn)里面調(diào)用的還是 dt_init,因?yàn)?dt_init 實(shí)現(xiàn)已被替換,實(shí)質(zhì)被實(shí)現(xiàn)的是 init

2.刪除
既然我們使用它來 swizzling 方法,那么我們在 swizzling 完后某一時(shí)間我們不需要了,要回到原來的實(shí)現(xiàn),這時(shí)候我們該怎么做呢?平??梢约觽€(gè)開關(guān)來決定是否操作,但是隨著代碼的累加,業(yè)務(wù)的增多。這將會變得很亂,管理很難。所以我們必須想到一個(gè)好的辦法來解決。辦法就是通過 runtime 的一個(gè)函數(shù) class_copyMethodList ,來遍歷出他所有的 Method,我們之前說過一個(gè) Method 就是一個(gè)結(jié)構(gòu)體指針,所以內(nèi)部參數(shù) Imp 和 Method 一一對應(yīng)的, 我們只需在 swizzling 的時(shí)候保存下 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;
    });
}

以上代碼就是恢復(fù)原來的實(shí)現(xiàn)的代碼:

1.) restore 改方法需手動(dòng)調(diào)用才可以恢復(fù);
2.)同樣使用 dispatch_once_t 方法,確保執(zhí)行一次。

Method Sizzling 類簇使用

開發(fā)中常用的 NSString、NSArray、NSDictionary 其實(shí)都是類簇(一組隱藏在公共接口下的私有類),所以對類簇進(jìn)行 swizzling 時(shí)要注意 class 為類簇管理下的那個(gè)私有類。例如在開發(fā)中常遇到 NSDictionary 用字面量創(chuàng)建時(shí),當(dāng) key 或者 value 為 nil 時(shí),程序會 crash。這里我們 swizzling 他的初始化方法將 key 或者 value 為 nil 的情況全部替換為 NSNull 的一個(gè)實(shí)例,這樣不但使程序更加健壯,并且方便了我們開發(fā)調(diào)試。

@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 管理下的的一個(gè)私有類 __NSPlaceholderDictionary ,而方法為initWithObjects:forKeys:count:,

結(jié)語
雖然 swizzling 解決了我們一些難以解決的棘手問題,讓我們開發(fā)走上了一些捷徑,但是我們要嚴(yán)謹(jǐn)?shù)膶Υ褂茫龅接性O(shè)計(jì)的使用。畢竟在一些黑魔法被濫用后造成的糟糕的結(jié)果是無法估量的。

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

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

  • Method Swizzling已經(jīng)被聊爛了,都知道這是Objective-C的黑魔法,可以交換兩個(gè)方法的實(shí)現(xiàn)。今...
    Sunxb閱讀 456評論 0 1
  • Objective-C Method Swizzling增強(qiáng)注釋版。有些代碼可能拿過來能直接用,但是我們并不知道其...
    帥氣的阿斌閱讀 237評論 0 0
  • 我們常常會聽說 Objective-C 是一門動(dòng)態(tài)語言,那么這個(gè)「動(dòng)態(tài)」表現(xiàn)在哪呢?我想最主要的表現(xiàn)就是 Obje...
    Ethan_Struggle閱讀 2,345評論 0 7
  • 該文章屬于劉小壯原創(chuàng),轉(zhuǎn)載請注明:劉小壯[http://www.itdecent.cn/u/2de707c93d...
    劉小壯閱讀 43,855評論 141 272
  • 文中的實(shí)驗(yàn)代碼我放在了這個(gè)項(xiàng)目中。 以下內(nèi)容是我通過整理[這篇博客] (http://yulingtianxia....
    茗涙閱讀 1,028評論 0 6

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