0

我正在尝试NSHipster Fake Book的代码示例来调整 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
4

1 回答 1

2

因为load是类方法,所以selfinClass cls = object_getClass(self);指的是 的UIViewController,而不是您想要的实际类 ( UIViewController)。

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

于 2018-08-19T19:12:14.783 回答