美文网首页
【iOS开发】手把手教你用runtime替换掉类中现有的方法

【iOS开发】手把手教你用runtime替换掉类中现有的方法

作者: Huangbaoqin | 来源:发表于2017-09-14 21:45 被阅读13次
    • 首先,看需求
    #import <Foundation/Foundation.h>
    
    @interface MethodsSwizzlingClass : NSObject
    
    - (void)method_A;
    
    - (void)method_B;
    
    @end
    
    #import "MethodsSwizzlingClass.h"
    
    @implementation MethodsSwizzlingClass
    
    - (void)method_A {
        NSLog(@"A");
    }
    
    - (void)method_B {
        NSLog(@"B");
    }
    
    @end
    

    需求:交换 method_A 和 method_B 的实现(调用 method_A 控制台打印出B)

    • 好,怎么实现?
    #import "MethodsSwizzlingClass.h"
    #import <objc/runtime.h> // 添加runtime头文件
    
    @implementation MethodsSwizzlingClass
    
    // 在load方法中交换method_A 和 method_B 的实现
    + (void)load {
        Method originMethod = class_getInstanceMethod([MethodsSwizzlingClass class], @selector(method_A));
        Method replaceMethod = class_getInstanceMethod([MethodsSwizzlingClass class], @selector(method_B));
        method_exchangeImplementations(originMethod, replaceMethod);
    }
    
    - (void)method_A {
        NSLog(@"A");
    }
    
    - (void)method_B {
        NSLog(@"B");
    }
    

    当调用method_A就打印出B了

    MethodsSwizzlingClass *class = [[MethodsSwizzlingClass alloc] init];
    [class method_A];
    
    • too sample?naive?

    其实呢,现在你已经知道如何交换两个方法的实现了,如果自己实现一个不知道什么方法和系统中的方法交换的话,那么不就可以顶替掉系统中的方法了吗?而且你还可以在不需要知道系统方法源码的情况下为其添加新功能。怎么样?惊不惊喜?意不意外?嘻嘻嘻

    • 举一个典型的🌰

    页面跳转后,打印出当前ViewController的类名,这对于熟悉一份陌生代码还是有帮助的,能够提高你的姿势水平

    • emmm,怎么实现?
      • 首先,创建UIViewController的拓展类
      • 然后呢,实现viewDidAppear的替代方法
      • 最后,和viewDidAppear方法交换实现
    #import "UIViewController+log.h"
    #import <objc/runtime.h>
    
    @implementation UIViewController (log)
    
    + (void)load {
        Method originMethod = class_getInstanceMethod([self class], @selector(viewDidAppear:));
        Method replaceMethod = class_getInstanceMethod([self class], @selector(viewDidAppear_huang:));
        method_exchangeImplementations(originMethod, replaceMethod);
    }
    
    - (void)viewDidAppear_huang:(BOOL)animated {
        [self viewDidAppear_huang:animated];
        NSLog(@"current class ---> %@", NSStringFromClass([self class]));
    }
    
    @end
    

    简单粗暴到没朋友,先这样吧

    相关文章

      网友评论

          本文标题:【iOS开发】手把手教你用runtime替换掉类中现有的方法

          本文链接:https://www.haomeiwen.com/subject/oqkjsxtx.html