#import <objc/runtime.h>
1. 替换类方法:
+ (void)load
{
Class class = object_getClass([ClassName class]);
Method originalMethod =class_getClassMethod(class,@selector(method1));
Method newMethod =class_getClassMethod(class,@selector(method2));
BOOL didAddMethod =class_addMethod(class,@selector(method1),method_getImplementation(newMethod),method_getTypeEncoding(newMethod));
if(didAddMethod) { class_replaceMethod(class,@selector(method2),method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, newMethod);
}
}
2. 替换实例方法:
+(void)initialize
{
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
Class class = UIViewController.class;
Method originalMethod =class_getInstanceMethod(class,@selector(method1));
Method newMethod =class_getInstanceMethod(class,@selector(method2));
BOOL didAddMethod =class_addMethod(class,@selector(method1),method_getImplementation(newMethod),method_getTypeEncoding(newMethod));
if(didAddMethod) { class_replaceMethod(class,@selector(method2),method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, newMethod);
}
});
}
3. 查看类的方法列表:
unsignedintcount;
Method*methods =class_copyMethodList(class, &count);
for(inti =0; i < count; i++) {
NSLog(@"%s", sel_getName(method_getName(methods[i])));
}