iOS_MethodSwizzling_ ブラック マジック ピットとソリューション

ピット ポイント 1: 複数のメソッド交換により、メソッドが元の実装に置き換えられます

解決策: 単利を使用して制限し、メソッド交換は 1 つだけにします

// 解决坑点1
+ (void)load{
    
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    
    
        [RuntimeTool wsk_methodSwizzlingWithClass:self oriSEL:@selector(wsk_oriFunction) swizzledSEL:@selector(wsk_swiMethodFunction)];
    });
}

ピット ポイント 2: 古い交換方法、サブクラスが実装されておらず、親クラスが実装されている

問題: 親クラスが古いメソッドを呼び出すと、クラッシュする.
解決策: 最初にメソッドを追加し、追加が成功した場合は < repleace> を置き換え、そうでない場合は < exchange> を置き換えます。

ピット ポイント 3: サブクラスも親クラスも実装されていない交換方法

問題: 無限ループが発生する
解決策: 古いメソッドが である場合nilswizzeldSEL置き換え後に何もしない空の実装がコピーされます。

コードは以下のように表示されます:

#import "RuntimeTool.h"
#import <objc/runtime.h>

@implementation RuntimeTool
+ (void)wsk_methodSwizzlingWithClass:(Class)cls oriSEL:(SEL)oriSEL swizzledSEL:(SEL)swizzledSEL{
    
    
    if (!cls) NSLog(@"传入的交换类不能为空");
    
    Method oriMethod = class_getInstanceMethod(cls, oriSEL);
    Method swiMethod = class_getInstanceMethod(cls, swizzledSEL);
    
    // 解决坑点3
    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
	// 解决坑点2
    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);
    }
}
@end



おすすめ

転載: blog.csdn.net/FlyingKuiKui/article/details/121580157