为什么这个UIViewController方法混乱不起作用?

时间:2018-08-19 16:53:33

标签: ios objective-c method-swizzling

我正在尝试 NSHipster伪书 的代码示例,以简化UIViewController的viewWillAppear:方法。但是似乎似乎无法正常工作,因为从未调用过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 个答案:

答案 0 :(得分:2)

由于load是一个类方法,所以self中的Class cls = object_getClass(self);是指UIViewController meta 类,而不是您实际使用的类想要(UIViewController

如果将其更改为Class cls = [self class];,则cls将是UIViewController类本身,它应该可以工作。