iOS开发征服iOS

method_exchangeImplementations交换

2015-11-10  本文已影响3340人  jiangamh

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。

上一篇 下一篇

猜你喜欢

热点阅读