1

我想在 Objective C 中测试方法 swizzling:

goodName1.添加方法AViewController

#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.添加调酒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

有什么地方不对吗?谢谢。

4

1 回答 1

0

您正在尝试在 AViewController 中调配方法,但您将代码放入+(void)load基本 UIViewController。这些是两个独立的类对象,因此您需要+(void)load为 AViewController 执行此操作。

于 2018-02-02T10:03:32.817 回答