勤能补拙之多敲出代码
// * Returns a specified instance method for a given class.
方法一:Method class_getInstanceMethod(Class cls, SEL name)
// * Returns the implementation of a method.
方法二:IMP method_getImplementation(Method m)
// * Returns a string describing a method's parameter and return types.
方法三:const char method_getTypeEncoding(Method m)
// * Adds a new method to a class with a given name and implementation.
方法四:BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
// * Replaces the implementation of a method for a given class.
方法五:IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
// * Exchanges the implementations of two methods.
方法六:void method_exchangeImplementations(Method m1, Method m2)
#import "Test.h"
#import <objc/runtime.h>
void SwizzleMethod(Class clazz, SEL origin, SEL current) {
Method originMethod = class_getInstanceMethod(clazz, origin);
Method currentMethod = class_getInstanceMethod(clazz, current);
IMP originIMP = method_getImplementation(originMethod);
IMP currentIMP = method_getImplementation(currentMethod);
const char * originType = method_getTypeEncoding(originMethod);
const char * currentType = method_getTypeEncoding(currentMethod);
BOOL success = class_addMethod(clazz, origin, currentIMP, currentType);
if (success) {
class_replaceMethod(clazz, current, originIMP, originType);
} else {
method_exchangeImplementations(originMethod, currentMethod);
}
}
@implementation Test
+ (void)load {
SwizzleMethod([self class], @selector(method1), @selector(method2));
SwizzleMethod([self class], @selector(method1), @selector(method3));
}
- (void)method1 {
NSLog(@"a");
}
- (void)method2 {
NSLog(@"b");
[self method2];
}
- (void)method3 {
NSLog(@"c");
[self method3];
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Test *text = [[Test alloc] init];
[text method1];
NSLog(@"---------------------");
[text method2];
NSLog(@"---------------------");
[text method3];
}