1. Class object_getClass(id obj)
获取isa指向的class
NSPerson *person = [[NSPerson alloc] init];
NSLog(@"%p %p",
object_getClass(person),
object_getClass(object_getClass(person))
);
//log
2020-08-29 18:13:25.156169+0800 runtime_API[13610:390470] 0x1000020f0 0x1000020c8
2. Class object_setClass(id obj, Class cls)
设置isa指向的class
NSPerson *person = [[NSPerson alloc] init];
object_setClass(person, NSCar.class);
NSLog(@"%@", object_setClass(person, NSCar.class));
[person run];
// log
2020-08-29 18:21:24.521334+0800 runtime_API[13712:397596] NSCar
2020-08-29 18:21:24.521394+0800 runtime_API[13712:397596] -[NSCar run]
3. BOOL object_isClass(id obj)
判断一个oc对象是否class
NSLog(@"%d %d %d",object_isClass(person),
object_isClass(object_getClass(person)),
object_isClass(object_getClass(object_getClass(person)))
);
//log
2020-08-29 19:17:35.832826+0800 runtime_API[14234:426760] 0 1 1
4.1. Ivar class_getInstanceVariable(Class cls, const char * name)
获取示例变量信息
4.2. id object_getIvar(id obj, Ivar ivar)
获取成员变量的值
4.3. void object_setIvar(id obj, Ivar ivar, id value)
设置成员变量的值
4.4. void object_setIvarWithStrongDefault(id obj, Ivar ivar, id value)
设置成员变量的值(默认strong)
//获取示例变量信息
Ivar age_ivar = class_getInstanceVariable(NSPerson.class, "_age");
const char *age_name = ivar_getName(age_ivar);
const char *age_type = ivar_getTypeEncoding(age_ivar);
NSLog(@"%s %s", age_name,age_type);
//设置和获取成员变量的值
//age
object_setIvar(person, age_ivar, (__bridge id)(void *)27);
id age = object_getIvar(person, age_ivar);
NSLog(@"%d %d %@",person.age, (int)age,[person valueForKey:@"_age"]);
//name
Ivar name_ivar = class_getInstanceVariable(NSPerson.class, "_name");
object_setIvar(person, name_ivar, @"bien");
id name = object_getIvar(person, name_ivar);
NSLog(@"%@ %@ %@",name,person.name,[person valueForKey:@"_name"]);
//设置成员变量的值(默认strong)
object_setIvarWithStrongDefault(person, name_ivar, @"wbn");
NSLog(@"%@",person.name);
//log
2020-08-29 20:23:18.234092+0800 runtime_API[15160:476832] _age i
2020-08-29 20:23:18.234382+0800 runtime_API[15160:476832] 27 27 27
2020-08-29 20:23:18.234551+0800 runtime_API[15160:476832] bien bien bien
2020-08-29 20:40:01.942927+0800 runtime_API[15301:488642] wbn
ARC不可用
id object_copy(id obj, size_t size) OBJC_ARC_UNAVAILABLE;
id object_dispose(id obj) OBJC_ARC_UNAVAILABLE;
Ivar object_setInstanceVariable(id obj, const char * name, void * value)
Ivar object_setInstanceVariableWithStrongDefault(id obj,const char * name,void * value)
Ivar object_getInstanceVariable(id obj, const char * name, void * * outValue)