美文网首页
Runtime方法交换

Runtime方法交换

作者: CrazySnow | 来源:发表于2023-05-18 09:58 被阅读0次

作用:替换系统方法,便于在系统方法内书写自己的逻辑
方式:一般创建对应系统类的类别,然后在+load里写替换逻辑
注意点:慎用,别的地方会调用,可能会出现未知错误
在自己写的替换方法里要调用一次自己,保证系统方法原有逻辑的实现

eg: UIApplication中的workspace:willDestroyScene:withTransitionContext:completion:替换

+(void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class _class = UIApplication.class;
        
        SEL _originSelector = @selector(workspace:willDestroyScene:withTransitionContext:completion:);
        SEL _newSelector = @selector(lzj_workspace:willDestroyScene:withTransitionContext:completion:);
        
        Method oriMethod = class_getInstanceMethod(_class, _originSelector);
        Method newMethod = class_getInstanceMethod(_class, _newSelector);
        if (!newMethod) {
            return;
        }
        
        BOOL isAddedMethod = class_addMethod(_class, _originSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
        if (isAddedMethod) {
            // 如果 class_addMethod 成功了,说明之前 fromClass 里并不存在 originSelector,所以要用一个空的方法代替它,以避免 class_replaceMethod 后,后续 toClass 的这个方法被调用时可能会 crash
            IMP oriMethodIMP = method_getImplementation(oriMethod) ?: imp_implementationWithBlock(^(id selfObject) {});
            const char *oriMethodTypeEncoding = method_getTypeEncoding(oriMethod) ?: "v@:";
            class_replaceMethod(_class, _newSelector, oriMethodIMP, oriMethodTypeEncoding);
        } else {
            method_exchangeImplementations(oriMethod, newMethod);
        }
    });

}
- (void)lzj_workspace:(id)workspace willDestroyScene:(id)scene withTransitionContext:(id)context completion:(id)completion {
    [self lzj_workspace:workspace willDestroyScene:scene withTransitionContext:context completion:completion];
    NSLog(@"test");
    
}

相关文章

  • runtime

    runtime交换方法 动态添加方法

  • runTime常用方法

    使用runTime改变实例成员的值 使用runtime来交换两个方法 注意再次调用该方法不交换 使用runTime...

  • Runtime

    runtime运行时机制1:通过runtime,实现方法交换(交换两个类方法、交换两个实例方法)2:通过runti...

  • Day3

    1 runtime运行时机制1:通过runtime,实现方法交换(交换两个类方法、交换两个实例方法)。2:通过ru...

  • runtime的理解(二)

    主要内容 利用 runtime 交换方法 利用 runtime 动态添加方法 利用 runtime 动态添加属性 ...

  • 查看SDK调用支付宝参数

    使用runtime 方法交换openurl

  • objc runtime (四)动态添加属性

    在《objc runtime (二)交换方法》中我提到过runtime最实用的就是交换方法和动态添加属性两个用法。...

  • iOS runtime如何交换两个类方法

    如有转载,请标明出处:iOS runtime如何交换两个类方法 runtime交换实例方法,老生常谈的问题,很多b...

  • iOS -- runtime的应用

    runtime主要有一下几种应用场景 方法交换 添加属性 (一)方法交换 (1)字体适配 方法交换实际交换的是方法...

  • runtime和oc内存区域(2018-04-02)

    runtime常用的几个方法: 交换方法 动态添加属性 动态添加方法 1.交换方法 class_getClassM...

网友评论

      本文标题:Runtime方法交换

      本文链接:https://www.haomeiwen.com/subject/vppwsdtx.html