我正在尝试 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
答案 0 :(得分:2)
由于load
是一个类方法,所以self
中的Class cls = object_getClass(self);
是指UIViewController
的 meta 类,而不是您实际使用的类想要(UIViewController
。
如果将其更改为Class cls = [self class];
,则cls
将是UIViewController
类本身,它应该可以工作。