美文网首页iOS开发征服iOS
method_exchangeImplementations交换

method_exchangeImplementations交换

作者: jiangamh | 来源:发表于2015-11-10 17:43 被阅读3340次

method_exchangeImplementations作用:method_exchangeImplementations可以交换两个方法的具体实现,先举个例子,再解释。

@implementation ViewController

- (void)viewDidLoad

{

       [super viewDidLoad];

       [self methodExchange];

       [self method1];

       [self method2];

}

-(void)method1

{

          NSLog(@"method1");

}

-(void)method2

{

          NSLog(@"method2");

}

-(void)methodExchange

{

        Method method1 = class_getInstanceMethod([self class], @selector(method1));

        Method method2 = class_getInstanceMethod([self class], @selector(method2));

       //交换method1和么thod的IMP指针,(IMP代表了方法的具体的实现)  

       method_exchangeImplementations(method1, method2);

}

@end

运行截图如下:

[self method1]输出method2,[self method2]输出method1。

原理如下:

@selector(method1) ------->IMP1(函数指针,具体实现输出么method1)

@selector(method2) ------->IMP1(函数指针,具体实现输出么method2)

当执行method_exchangeImplementations(method1, method2)变成如下:

@selector(method1) ------->IMP2(函数指针,具体实现输出么method2)

@selector(method2) ------->IMP1(函数指针,具体实现输出么method1)

所以,[self method1]输出method2,[self method2]输出method1。

相关文章

网友评论

  • 茄子重新开始:我想问下 要是一个方法是带参数的呢 我这边试的是会报错
  • MoussyL:-(void)methodExchange 这个方法里的 Method 是什么 ,用它定义 ,是个自定义的类么? 如果是自定义类 也应该是 Method *method1 呀。。。表示很疑惑
    MoussyL:@木子夕 已经查到了,是runtime里的,感谢楼主的分享,涨知识了,提一点建议,文章写的太含蓄了,希望以后分享的东西能更直白一些 哈哈 ~~ :grin:
  • 2bb5b8da62ea:能不能注释一下啊大帅哥
    jiangamh:@Andyhuige 以后会注意点,谢谢指点。

本文标题:method_exchangeImplementations交换

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