OGeek|极客世界-中国程序员成长平台

标题: ios swizzle 更好理解 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:59
标题: ios swizzle 更好理解

我有一个带有此代码的 UIViewController:

- (void)viewDidAppearBOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"CLASIC");
}

然后我有一个带有 UIViewController 类别的框架,它以这种方式运行:

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        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_viewDidAppearBOOL)animated
{
    [self logged_viewDidAppear:animated];

    NSLog(@"SWIZZLED");
}

输出是 SWIZZLED,然后是 CLASIC。

现在我的问题是:如果在我的 View Controller 中我评论了 [super viewDidAppear:animated];然后不再调用 swizzled 方法;这是为什么?我理解了大部分方面,但似乎这一方面不知何故滑倒了。

- (void)viewDidAppearBOOL)animated
{
    // we comment this and this will trigger the swizzled method not being called anymore
    //[super viewDidAppear:animated];
    NSLog(@"CLASIC");
}

// ========================

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        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_viewDidAppearBOOL)animated
{
    [self logged_viewDidAppear:animated];

    NSLog(@"SWIZZLED");
}



Best Answer-推荐答案


方法调配用于在运行时用自定义方法覆盖原始方法。因此,您几乎可以将任何方法(包括私有(private)苹果实现的方法)与您编写的自定义方法进行交换。

所以想象有一个名为 Parent 的类有一个名为 A 的方法,然后你在某个地方与 B 交换它,然后像在里面一样调用它加载方法。从现在开始,'Parent' 之外的每个子类都将使用 B 除了原始的 'A' 方法。但是,如果您在子类中覆盖 A 怎么办?作为继承定义,对象将调用它们的自己的方法,如果它们没有实现它,它们会使用它们的父类(super class)的方法。那么如果你想要父实现呢?这就是 super 的用武之地。

结论

在这个问题的情况下:

希望对你有帮助

关于ios swizzle 更好理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53188675/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4