zoukankan      html  css  js  c++  java
  • iOS开发Runtime 方法替换

    通过#import <objc/runtime.h>我们可以找到:

     1 /** 
     2  * Returns a specified instance method for a given class.
     3  * 
     4  * @param cls The class you want to inspect.
     5  * @param name The selector of the method you want to retrieve.
     6  * 
     7  * @return The method that corresponds to the implementation of the selector specified by 
     8  *  e name for the class specified by e cls, or c NULL if the specified class or its 
     9  *  superclasses do not contain an instance method with the specified selector.
    10  *
    11  * @note This function searches superclasses for implementations, whereas c class_copyMethodList does not.
    12  */
    13 OBJC_EXPORT Method _Nullable
    14 class_getInstanceMethod(Class _Nullable cls, SEL _Nonnull name)
    15     OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);
    class_getInstanceMethod这个可以获取类的实例方法

    #import <Foundation/Foundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface RuntimeObjc : NSObject
    
    
    -(void)runEg;
    -(void)otherRunEg;
    
    @end
    
    #import "RuntimeObjc.h"
    #import <objc/runtime.h>
    
    @implementation RuntimeObjc
    
    +(void)load{
        
        Method runEg = class_getInstanceMethod(self, @selector(runEg));
        Method otherRunEg = class_getInstanceMethod(self, @selector(otherRunEg));
      //交换 method_exchangeImplementations(runEg, otherRunEg); } -(void)runEg{ NSLog(@"runEg"); } -(void)otherRunEg{
      NSLog(@"otherRunEg");
      [self otherRunEg];//已经做了置换 故调用的runEg
       
    }
    @end

    调用

        RuntimeObjc * objc = [[RuntimeObjc alloc]init];
        [objc runEg];
    

     打印:

    2020-05-21 15:42:43.416766+0800 11111[35733:176260] otherRunEg
    2020-05-21 15:42:43.416928+0800 11111[35733:176260] runEg
    

     





  • 相关阅读:
    关于Design Complier/Library Compiler的跌坑(坑爹)记录
    博客暂时停更
    简单的Verilog测试模板结构
    存储器的设计/建模
    静态时序分析的三种分析模式(简述)
    Linux系统的基本使用
    Modelsim的使用——复杂的仿真
    Python-第三方库requests
    MySQL查询结果写入到文件总结
    MySQL创建函数报“ERROR 1418 ”错误,不能创建函数
  • 原文地址:https://www.cnblogs.com/guozhihe/p/12931301.html
Copyright © 2011-2022 走看看