RunTime运行时之动态替换和改变方法实现 发表于 2016-10-25 | 分类于 iOS RunTime运行时之动态替换和改变方法实现123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475#import "ViewController.h"#import <objc/runtime.h>@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];//获取方法所有名[self getMethodName];//添加方法[self addMethod];//替换方法[self changeMethod];//改变方法实现[self changeMethodImpl];//方法实现改变后调用实验[self method_1];}#pragma 获取方法名- (void)getMethodName{void (*useMethod)(id,SEL);unsigned int outCount = 0;Method *methods = class_copyMethodList([self class], &outCount);for(int i = 0;i < outCount;i++){Method method = methods[i];SEL sel = method_getName(method);NSLog(@"%s",sel_getName(sel));if(sel == @selector(method_1)){useMethod = (void (*)(id,SEL))[self methodForSelector:sel];useMethod(self,sel);}}}#pragma 添加方法- (void)addMethod{class_addMethod([self class], @selector(method::), (IMP)method_impl, "i@:i@");//此时调用方法需要用performSelector,否则编译器会报错[self performSelector:@selector(method::) withObject:@[@"piaojin",@(25)]];}#pragma 动态替换方法(也可以用于替换方法实现)- (void)changeMethod{//method_1与method_2进行替换method_exchangeImplementations(class_getInstanceMethod([self class], @selector(method_1)), class_getInstanceMethod([self class], @selector(method_2)));}#pragma 动态替换方法实现- (void)changeMethodImpl{//改变method_1的实现为method_3class_replaceMethod([self class], @selector(method_1), (IMP)method_3, "");}- (void)method_1{NSLog(@"method_1");}void method_impl(id self,SEL _cmd,NSString *str,int age){NSLog(@"str:%@,age:%d",str,age);}- (void)method_2{NSLog(@"method_2");}void method_3(){NSLog(@"method_3");}@end ------本文结束😘感谢阅读------