runtime-动态方法解析测试
2021-02-05 本文已影响0人
Berning
动态方法解析1
#import <Foundation/Foundation.h>
@interface NSPerson : NSObject
- (void)run;
+ (void)test;
@end
#import "NSPerson.h"
#import <objc/runtime.h>
@implementation NSPerson
+ (void)testImp
{
NSLog(@"%s",__func__);
}
- (void)runImp
{
NSLog(@"%s",__func__);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel == @selector(run)) {
Method method = class_getInstanceMethod(self, @selector(runImp));
return class_addMethod(self, sel, method_getImplementation(method), method_getTypeEncoding(method));
}
return [super resolveInstanceMethod:sel];
}
+ (BOOL)resolveClassMethod:(SEL)sel
{
if (sel == @selector(test)) {
Method method = class_getClassMethod(object_getClass(self),@selector(testImp) );
return class_addMethod(object_getClass(self), sel, method_getImplementation(method), method_getTypeEncoding(method));
}
return [super resolveClassMethod:sel];
}
@end
#import <Foundation/Foundation.h>
#import "NSPerson.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSPerson *person = [[NSPerson alloc] init];
[person run];
[NSPerson test];
}
return 0;
}
//log
2020-08-27 17:08:05.695237+0800 runtime[10652:398413] -[NSPerson runImp]
2020-08-27 17:08:05.695678+0800 runtime[10652:398413] +[NSPerson testImp]
Program ended with exit code: 0
动态方法解析2
#import <Foundation/Foundation.h>
@interface NSPerson : NSObject
- (void)run;
+ (void)test;
@end
#import "NSPerson.h"
#import <objc/runtime.h>
@implementation NSPerson
void runIMP(id self, SEL _cmd)
{
NSLog(@"%s",__func__);
}
void testIMP(id self, SEL _cmd)
{
NSLog(@"%s",__func__);
}
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel == @selector(run)) {
return class_addMethod(self, sel, (IMP)runIMP, "v16@0:8");
}
return [super resolveInstanceMethod:sel];
}
+ (BOOL)resolveClassMethod:(SEL)sel
{
if (sel == @selector(test)) {
return class_addMethod(object_getClass(self), sel, (IMP)testIMP, "v16@0:8");
}
return [super resolveClassMethod:sel];
}
@end
#import <Foundation/Foundation.h>
#import "NSPerson.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSPerson *person = [[NSPerson alloc] init];
[person run];
[NSPerson test];
}
return 0;
}
//log
2020-08-27 17:10:36.318523+0800 runtime[10680:399996] runIMP
2020-08-27 17:10:36.318962+0800 runtime[10680:399996] testIMP
Program ended with exit code: 0