method_exchangeImplementations(method1, method2)

method1和method2交换后,method1指向method2的实现,method2指向method1的实现,所以在向对象发送method1消息时执行的时method2的实现,在向method2发送消息时执行的是method1的实现。

#import "Person.h"
#import 

@implementation Person
- (void)introduce{
    NSLog(@"%@ %ld %@", self.name, self.age, self.gender == Male ? @"Male" : @"Female");
}
@end

@interface Person (runing)

@end

@implementation Person (runing)

+ (void)load{
    method_exchangeImplementations(class_getInstanceMethod(self, @selector(introduce)),class_getInstanceMethod(self, @selector(swizzling_introduce)));
}

- (void)swizzling_introduce{
    [self swizzling_introduce];//并不会引起循环调用,因为此时调用swizzing_introduce,实际执行的是introduce的实现。
    NSLog(@"this is a new method");
}

@end

你可能感兴趣的:(method_exchangeImplementations(method1, method2))