IOS知识积累移动端开发iOS底层

iOS底层原理21:Method-Swizzling方法交换

2021-08-12  本文已影响0人  黑白森林无间道

method-swizzling是什么?

如下图所示,交换前后的sel和imp的对应关系


image

method-swizzling涉及的相关API

method-swizzling使用过程中的问题分析

坑点1:method-swizzling使用过程中的一次性问题

所谓的一次性就是:mehod-swizzling写在load方法中,而load方法会主动调用多次,这样会导致方法的重复交换,使方法sel的指向又恢复成原来的imp的问题

解决方案

可以通过单例设计原则,使方法交换只执行一次,在OC中可以通过dispatch_once实现单例

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [HTRuntimeTool ht_bestMethodSwizzlingWithClass:self oriSEL:@selector(helloword) swizzledSEL:@selector(ht_studentInstanceMethod)];
    });
}

坑点2:子类没有实现,父类实现了

@interface HTPerson : NSObject

- (void)personInstanceMethod;

@end

@implementation HTPerson

- (void)personInstanceMethod {
    NSLog(@"person对象方法:%s", __func__);
}

@end
@interface HTTeacher : HTPerson

@end

/** HTTeacher.m 文件*/
#import "HTTeacher.h"
#import "HTRuntimeTool.h"

@implementation HTTeacher

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [HTRuntimeTool ht_methodSwizzlingWithClass:self oriSEL:@selector(personInstanceMethod) swizzledSEL:@selector(teacherInstanceMethod)];
    });
}

- (void)teacherInstanceMethod {
        // 是否会产生递归?--不会产生递归,原因是teacherInstanceMethod 会走 oriIMP,即personInstanceMethod的实现中去
    [self teacherInstanceMethod];
    NSLog(@"teacher对象方法:%s", __func__);
}

@end
+ (void)ht_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);
}
#import "ViewController.h"
#import "HTTeacher.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    HTTeacher *t = [HTTeacher alloc];
    [t personInstanceMethod];
    
    HTPerson *p = [HTPerson alloc];
    [p personInstanceMethod];
}

@end
image image

优化:避免imp找不到

通过class_addMethod尝试添加你要交换的方法

+ (void)ht_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);
    }
}
image image
image
image

其中class_replaceMethodclass_addMethod中都调用了addMethod方法,区别在于bool值的判断,下面是addMethod的源码实现

/**********************************************************************
* addMethod
* fixme
* Locking: runtimeLock must be held by the caller
**********************************************************************/
static IMP 
addMethod(Class cls, SEL name, IMP imp, const char *types, bool replace)
{
    IMP result = nil;

    runtimeLock.assertLocked();

    checkIsKnownClass(cls); // 检查是否是已知类
    
    ASSERT(types);
    ASSERT(cls->isRealized());

    method_t *m;
    if ((m = getMethodNoSuper_nolock(cls, name))) {
        // already exists 已经存在
        if (!replace) {
            // 添加方法:直接返回要添加的方法实现
            result = m->imp(false);
        } else {
            // 替换方法:返回替换之前的方法实现
            result = _method_setImplementation(cls, m, imp);
        }
    } else { // 不存在
        // fixme optimize
        // 新建一个method_list,添加方法
        method_list_t *newlist;
        newlist = (method_list_t *)calloc(method_list_t::byteSize(method_t::bigSize, 1), 1);
        newlist->entsizeAndFlags = 
            (uint32_t)sizeof(struct method_t::big) | fixed_up_method_list;
        newlist->count = 1;
        auto &first = newlist->begin()->big();
        first.name = name;
        first.types = strdupIfMutable(types);
        first.imp = imp;
        // 对rwe进行处理,将增的newlist加进去
        addMethods_finish(cls, newlist);
        result = nil;
    }

    return result;
}

坑点3:子类没有实现,父类也没有实现,下面的调用有什么问题?

在调用personInstanceMethod方法时,父类HTPerson中只有声明,没有实现,子类HTTeacher中既没有声明,也没有实现

image

原因是 栈溢出,递归死循环了,那么为什么会发生递归呢?----主要是因为

image

优化:避免递归死循环

如果oriMethod为空,为了避免方法交换没有意义,而被废弃,需要做一些事情

+ (void)ht_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最常用的应用是防止数组、字典等越界崩溃

在iOS中NSNumberNSArrayNSDictionary等这些类都是类簇,一个NSArray的实现可能由多个类组成。所以如果想对NSArray进行Swizzling,必须获取到其“真身”进行Swizzling,直接对NSArray进行操作是无效的

类名 真身
NSArray __NSArrayI
NSMutableArray __NSArrayM
NSDictionary __NSDictionaryI
NSMutableDictionary __NSDictionaryM

NSArray防崩溃处理

#import "NSArray+HT.h"
#import <objc/runtime.h>

@implementation NSArray (HT)

//如果下面代码不起作用,造成这个问题的原因大多都是其调用了super load方法。在下面的load方法中,不应该调用父类的load方法。这样会导致方法交换无效
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method fromMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));
        Method toMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(ht_objectAtIndex:));
        method_exchangeImplementations(fromMethod, toMethod);
    });
   
}

- (id)ht_objectAtIndex:(NSUInteger)index{
    //判断下标是否越界,如果越界就进入异常拦截
    if (self.count-1 < index) {
        // 这里做一下异常处理,不然都不知道出错了。
#ifdef DEBUG  // 调试阶段
        return [self ht_objectAtIndex:index];
#else // 发布阶段
        @try {
            return [self ht_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 ht_objectAtIndex:index];
    }
}

@end
NSArray *array = @[@"1", @"2", @"3"];
[array objectAtIndex:3];
image
上一篇 下一篇

猜你喜欢

热点阅读