在不同类之间实现Method Swizzling

首先,获取目标类方法,即当前类交换方法

Class originalClass = [TXUGCRecord class];
    Class swizzledClass = [self class];
    SEL originalSelector = @selector(stopBGM);
    SEL swizzledSelector = @selector(swizzled_stopBGM);
    Method originalMethod = class_getInstanceMethod(originalClass, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(swizzledClass, swizzledSelector);

然后向目标类中新添加一个新方法

    BOOL registerMethod = class_addMethod(originalClass,
                                          swizzledSelector,
                                          method_getImplementation(swizzledMethod),
                                          method_getTypeEncoding(swizzledMethod));
    if (!registerMethod) {
        return;
    }

注意,添加完方法后,需要更新swizzledMethod变量,获取当前Car类中xxx_run:的Method指针

    swizzledMethod = class_getInstanceMethod(originalClass, swizzledSelector);
    if (!swizzledMethod) {
        return;
    }

后续流程与之前的一致

    BOOL didAddMethod = class_addMethod(originalClass,
                                        originalSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));
    if (didAddMethod) {
        class_replaceMethod(originalClass,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }

你可能感兴趣的:(在不同类之间实现Method Swizzling)