gpt4 book ai didi

objective-c - Objective-C 中的方法调配

转载 作者:行者123 更新时间:2023-12-03 18:33:43 25 4
gpt4 key购买 nike

我读了一篇 article about "Method Swizzling in Objective-C" .本文中“Method 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]);
}

在文章中,有一句话是

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.

但是我不是很清楚这个说法,是不是意味着当我们这样写代码的时候:

[self viewDidAppear], 

因为它的实现变成了“logged_viewDidAppear”,所以程序转到方法“logged_viewDidAppear”,在那个方法中我们可以看到,第一行是[self logged_viewDidAppear:animated];出于同样的原因,该方法变为“viewDidAppear”。我的话对吗?

最佳答案

是的。当调用 viewDidAppear 时,它实际上会在运行时调配到 logged_viewDidAppear 的实现,调用 logged_viewDidApear 也是如此。

检查这个:http://nshipster.com/method-swizzling/和这个 https://www.bignerdranch.com/blog/inside-the-bracket-part-7-runtime-machinations/

关于objective-c - Objective-C 中的方法调配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32432506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com