// ExampleA.h // #import <Foundation/Foundation.h> @interface ExampleA : NSObject - (void)methodA; @end
// // ExampleA.m // #import "ExampleA.h" @implementation ExampleA - (void)methodA { NSLog(@"methodA"); } @end
// // ExampleB.h // #import <Foundation/Foundation.h> @interface ExampleB : NSObject - (void)test; @end
// // ExampleB.m // #import "ExampleB.h" #import <objc/objc-class.h> #import "ExampleA.h" @implementation ExampleB - (void)test { ExampleA *theA = [ExampleA new]; NSLog(@"First call:"); [theA methodA]; SEL theMethodASelector = @selector(methodA); Method theMethodA = class_getInstanceMethod([ExampleA class], theMethodASelector); SEL theMethodBSelector = @selector(methodB); Method theMethodB = class_getInstanceMethod([ExampleB class], theMethodBSelector); method_setImplementation(theMethodA, method_getImplementation(theMethodB)); NSLog(@"Second call:"); [theA methodA]; } - (void)methodB { NSLog(@"methodB"); } @end
First call: methodA Second call: methodB