3

我读了一篇关于“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]);
}

文章中有一句话是

看起来这个方法对自身进行了无意义的递归调用,但在我们混合后它实际上不会这样做。

但是我对这个说法不是很清楚,是不是意味着当我们编写如下代码时:

[self viewDidAppear], 

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

4

1 回答 1

0

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

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

于 2015-09-07T07:11:27.133 回答