美文网首页
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方法交换

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