RunTime运行时之动态替换和改变方法实现

RunTime运行时之动态替换和改变方法实现


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#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

------本文结束😘感谢阅读------