#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_3
class_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
RunTime运行时之动态替换和改变方法实现
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 关于IoC容器和控制反转(也被称为依赖注入)模式以及Spring IoC的应用场景我在这里就不进行赘述了,下面直接...
- 【2017年10月7日-007-12】 ——读《战胜华尔街》每周小结week5 彼得.林奇作为一个著名的基金管理人...
