方法调配在 Objective C 中不起作用

Method swizzling doesn't work in Objective C

我想在 Objective C 中测试方法调配:

1.Add AViewController

中的方法 goodName
#import "AViewController.h"
#import "UIViewController+Tracking.h"
@interface AViewController ()

@end

@implementation AViewController
 - (void)viewDidLoad {
    [super viewDidLoad];
    [self goodName];
}
 - (void) goodName {
    NSLog(@"I am a good Name");
}
@end

2.Add 调配 goodName 方法的类别。

    #import "UIViewController+Tracking.h"
    #import <objc/runtime.h>
    #import "AViewController.h"
    @implementation UIViewController (Tracking)

    + (void) load {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            Class class = [self class];
            SEL originalSelector = @selector(goodName);
            SEL swizzledSelector = @selector(xxx_xxx_goodName);

            Method originalMethod = class_getInstanceMethod(class, originalSelector);
            Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

            BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));

            if (didAddMethod) {
                class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
            } else {
                method_exchangeImplementations(originalMethod, swizzledMethod);
            }

        });
    }

    - (void)xxx_xxx_goodName {
        NSLog(@"i am xxx goodName");
        [self xxx_xxx_goodName];
    }

    @end
  1. 如果一切正常,调用 goodName 将输出 i am xxx goodName,但它的输出是 I am a good Name.

有什么地方错了吗?谢谢。

您正试图调配 AViewController 中的方法,但您将代码放在 +(void)load 中用于基础 UIViewController。这是两个单独的 class 对象,因此您需要在 +(void)load 中为 AViewController 执行此操作。