其实也不咋常用,毕竟用runtime都少
#import <objc/runtime.h> 使用runtime之前一定要导入这个
Class object_getClass(id obj)
获取一个isa指针的指向,比如是实例对象,则调用之后返回类对象,类对象调用就返回 元类对象
Class object_setClass(id obj, Class cls);
#import "ViewController.h"
#import <objc/runtime.h>
@interface Person : NSObject
-(void)run;
@end
@implementation Person
-(void)run
{
NSLog(@"%s",__func__);
}
@end
@interface Human : NSObject
-(void)run;
@end
@implementation Human
-(void)run
{
NSLog(@"%s",__func__);
}
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *person = [[Person alloc] init];
object_setClass(person, [Human class]);
[person run]; // -[Human run]
// Do any additional setup after loading the view.
}
就是重定向,比如给person实例的isa重定向到Human,本质上就是修改isa指针
BOOL object_isClass(id obj);
Person *person = [[Person alloc] init];
NSLog(@"%d %d %d",object_isClass(person),object_isClass([Person class]),object_isClass(object_getClass([Person class]))); // 0 1 1
对象有三种分别是实例对象,类对象,元类对象,这个函数只能判断类对象,而元类对象是特殊的类对象,所以结果是0 1 1
就不一一介绍了
?
?值得一提的是,类一旦注册之后很多函数,比如addIvar就无法正常运行了,后续再给该类添加参数需要关联对象进行操作
|