OC提供了很多API来动态的获取class的类方法、实例方法、类名、实例名等,其原理就是利用runtime实现的
打开Runtime.h 我们可以看到
isa指针和objc_method_list的指针列表
isa的关系图如下:(该图来自这里)

实例isa指向类,类的isa指向元类,而类之间又是继承关系,元类之间也是继承关系,
所以只要传相应的类名就可以获取其类里面的所有实例或者方法而不需要知道它的代码。
Method Swizzling就是获取类里面的具体方法,然后可以进行覆盖,添加,修改等
上代码:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface father : NSObject
@end
@implementation father
-(void)printSome{
NSLog(@"father");
}
@end
@interface child : father
@end
@implementation child
-(void)printSome{
NSLog(@"child");
}
@end
@interface other : NSObject
+ (instancetype)personWithName;
@end
@implementation other
-(void)printSome{
NSLog(@"other");
}
+(instancetype)personWithName{
other *ot=[[other alloc]init];
return ot;
}
@end
int main(int argc, const char * argv[]) {
father *fa=[[father alloc]init];
[fa printSome];
father *ch=[[child alloc]init];
[ch printSome];
other *ot=[other personWithName];
[ot printSome];
Method oldMethod1=class_getInstanceMethod([father class], @selector(printSome));
Method newMethod1=class_getInstanceMethod([other class], @selector(printSome));
method_exchangeImplementations(oldMethod1, newMethod1);
[fa printSome];
[ot printSome];
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
}
return 0;
}
上面的方法:
class_getInstanceMethod 获取class的实例方法。
method_exchangeImplementations 交换两个方法
本文介绍了Objective-C中如何使用runtime API动态获取类的方法并进行替换,通过实例展示了class_getInstanceMethod和method_exchangeImplementations的使用方法,提供了一个在运行时修改类行为的实用技巧。
7888

被折叠的 条评论
为什么被折叠?



