Почему этот метод UIViewController Swizzling не работает?

Я пытаюсь использовать пример кода NSHipster Fake Book для viewWillAppear: метод UIViewController. Но похоже, что это не работает ожидаемо, так как xxx_viewWillAppear: метод никогда не вызывался. Я просто не могу понять почему. Пожалуйста, помогите мне, спасибо.

#import "ViewController.h"
#import <objc/runtime.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

@end

@implementation UIViewController (Tracking)
+(void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class cls = object_getClass(self);
        SEL originalSelector = @selector(viewWillAppear:);
        SEL swizzledSelector = @selector(xxx_viewWillAppear:);
        Method originalMethod = class_getInstanceMethod(cls, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(cls, swizzledSelector);
        BOOL addMethod = class_addMethod(cls, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (addMethod) {
            class_replaceMethod(cls, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        }
        else{
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

-(void)xxx_viewWillAppear:(BOOL)animated
{
    [self xxx_viewWillAppear:animated];
    NSLog(@"viewWillAppear: %@",self);
}
@end

1 ответ

Решение

Поскольку load это метод класса, self в Class cls = object_getClass(self); относится к мета- классу UIViewController, а не фактический класс, который вы хотите (UIViewController).

Если вы измените его на Class cls = [self class];, затем cls будет UIViewController сам класс и оно должно работать.

Другие вопросы по тегам