我读了article about "Method Swizzling in Objective-C"。在本文中,"方法Swizzing"是交换两种方法的实现。样本如下所示:
- (void) logged_viewDidAppear:(BOOL)animated {
[self logged_viewDidAppear:animated];
NSLog(@"logged view did appear for %@", [self class]);
}
+ (void)load {
static dispatch_once_t once_token;
dispatch_once(&once_token, ^{
SEL viewWillAppearSelector = @selector(viewDidAppear:);
SEL viewWillAppearLoggerSelector = @selector(logged_viewDidAppear:);
Method originalMethod = class_getInstanceMethod(self, viewWillAppearSelector);
Method extendedMethod = class_getInstanceMethod(self, viewWillAppearLoggerSelector);
method_exchangeImplementations(originalMethod, extendedMethod);
});
}
- (void) logged_viewDidAppear:(BOOL)animated {
[self logged_viewDidAppear:animated];
NSLog(@"logged view did appear for %@", [self class]);
}
在文章中,一句话是
看起来这个方法可能会对自己进行无意义的递归调用,但是在我们调整之后它实际上并没有这样做。
但是我对这个陈述不是很清楚,这是否意味着当我们编写如下代码时:
[self viewDidAppear],
因为它的实现变成了" logged_viewDidAppear"所以程序转到方法" logged_viewDidAppear",在我们可以看到的那个方法中,第一行是[self logged_viewDidAppear:animated] ;出于同样的原因,该方法变为" viewDidAppear"。我的话是否正确?
答案 0 :(得分:0)
是的。当调用viewDidAppear时,它实际上会在运行时被调换到logged_viewDidAppear的实现,因此被调用的是logged_viewDidApear。
检查:http://nshipster.com/method-swizzling/和此 https://www.bignerdranch.com/blog/inside-the-bracket-part-7-runtime-machinations/