Runtime应用之交换方法实现

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。

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我们常常会听说 Objective-C 是一门动态语言,那么这个「动态」表现在哪呢?我想最主要的表现就是 Obje...
    Ethan_Struggle阅读 6,572评论 0 7
  • 继上Runtime梳理(四) 通过前面的学习,我们了解到Objective-C的动态特性:Objective-C不...
    小名一峰阅读 4,114评论 0 3
  • 本文详细整理了 Cocoa 的 Runtime 系统的知识,它使得 Objective-C 如虎添翼,具备了灵活的...
    lylaut阅读 4,214评论 0 4
  • 文中的实验代码我放在了这个项目中。 以下内容是我通过整理[这篇博客] (http://yulingtianxia....
    茗涙阅读 4,457评论 0 6
  • 本文转载自:http://yulingtianxia.com/blog/2014/11/05/objective-...
    ant_flex阅读 4,164评论 0 1