美文网首页
Runtime应用之交换方法实现

Runtime应用之交换方法实现

作者: 执笔时光er | 来源:发表于2020-04-21 16:10 被阅读0次

Runtime一个常用的场景是交换方法的调用。其实就是利用了Runtime的方法交换,具体代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self doExchange];
    [ViewController doPrint1];
    // Do any additional setup after loading the view.
}

-(void)doExchange{
    Method originalMethod = class_getInstanceMethod([self class], @selector(doPrint1));
    Method swizzledMethod = class_getInstanceMethod([self class], @selector(doPrint2));
    
    method_exchangeImplementations(originalMethod, swizzledMethod);
}
+(void)doPrint1{
    NSLog(@"print-----------");
}
+(void)doPrint2{
    NSLog(@"print+++++++++++");
}

核心思路是先找到对应的Method,然后将其交换就OK。
上面实现的是交换实例方法,如果交换类方法的话,会发现Method是nil,这是因为类方法是存储在类所对应的源类的,代码需要修改一下:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self doExchange];
    [ViewController doPrint1];
    // Do any additional setup after loading the view.
}

-(void)doExchange{
    Method originalMethod = class_getInstanceMethod(objc_getMetaClass("ViewController"), @selector(doPrint1));
    Method swizzledMethod = class_getInstanceMethod(objc_getMetaClass("ViewController"), @selector(doPrint2));
    
    method_exchangeImplementations(originalMethod, swizzledMethod);
}
+(void)doPrint1{
    NSLog(@"print-----------");
}
+(void)doPrint2{
    NSLog(@"print+++++++++++");
}

核心还是先找到对应的Method,只不过类方法需要去到源类里面寻找,然后将其对应交换就OK。

我曾执笔雕刻时光 奈何良辰难书过往

相关文章

  • RunTime实现

    1:RunTiem交换方法实现 //runTime交换方法实现 // 1,创建已有类的分类,并且实现自己的方...

  • Runtime

    runtime运行时机制1:通过runtime,实现方法交换(交换两个类方法、交换两个实例方法)2:通过runti...

  • iOS - RunTime(Swift)

    RunTime实现存储属性(本质也是一个计算属性) RunTime实现方法交换

  • Day3

    1 runtime运行时机制1:通过runtime,实现方法交换(交换两个类方法、交换两个实例方法)。2:通过ru...

  • ios-Runtime(运行时)

    利用runtime来实现归档解档 方法交换 俗称 OC的方法欺骗 KVO的实现原理 用runtime来实现KVO...

  • iOS -- runtime的应用

    runtime主要有一下几种应用场景 方法交换 添加属性 (一)方法交换 (1)字体适配 方法交换实际交换的是方法...

  • iOS 防止方法未实现造成的崩溃

    实现原理基于runtime的方法交换和消息发送机制 方法交换 method_exchangeImplementat...

  • runtime 交换方法应用

    解决数组添加空值崩溃 解决字典添加空值崩溃 监控点击事件

  • Runtime应用之交换方法实现

    Runtime一个常用的场景是交换方法的调用。其实就是利用了Runtime的方法交换,具体代码如下: 核心思路是先...

  • Runtime实例运用-交换方法实现、Method Swizzl

    一.交换两个方法的实现: Runtime还可以交换两个方法的实现。例如:Person有两个方法:study、run...

网友评论

      本文标题:Runtime应用之交换方法实现

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