我正在学习方法调配。我理解一切,除非这样做,否则我会玩它:
#import <objc/runtime.h>
@implementation UIViewController (Tracking)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
// When swizzling a class method, use the following:
// Class class = object_getClass((id)self);
SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xxx_viewWillAppear:);
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);
}
});
}
#pragma mark - Method Swizzling
- (void)xxx_viewWillAppear:(BOOL)animated {
[self xxx_viewWillAppear:animated];
NSLog(@"viewWillAppear: %@", self);
}
@end
来源NSHipster。
在调用:
时,Objective C如何再次解析对原始函数的调用[self xxx_viewWillAppear:animated];
因为我们在调度表中调整了viewWillAppear所以这是如何完成的?我认为它会打电话给自己,但它不是。任何人都可以向我解释这最后一块拼图吗?
答案 0 :(得分:3)
调用
时[self xxx_viewWillAppear:animated];
你不再称呼自己,而是为
提供的原始实现viewWillAppear:animated
当你调整它们时,这两个实现“切换到了位置”。