Reputation: 117
I read an article about "Method Swizzling in Objective-C". In this article the meaning of "Method Swizzing" is to exchange the implementations of two methods. The sample is as below shows:
- (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]);
}
In the article, one sentence is
It may seem this this method makes a nonsensical recursive call to itself, but it won’t actually be doing that after we swizzle it.
But I am not very clear about this statement,does it mean that when we write the code like below:
[self viewDidAppear],
since its implementation became "logged_viewDidAppear", so the program goes to method "logged_viewDidAppear", and in that method as we can see, the first line is [self logged_viewDidAppear:animated]; for the same reason, the method becomes "viewDidAppear". Is my word correct?
Upvotes: 3
Views: 6060
Reputation: 545
Yep. When viewDidAppear is called, it actually would be swizzled to the implementation of logged_viewDidAppear at runtime, so does logged_viewDidApear being called.
Check this:http://nshipster.com/method-swizzling/ and this https://www.bignerdranch.com/blog/inside-the-bracket-part-7-runtime-machinations/
Upvotes: 0