Runtime的本质(六)---常用的API
Runtime的一些常用API
Runtime API - 01 – 类
动态创建一个类(参数:父类,类名,额外的内存空间)
Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)
注册一个类(要在类注册之前添加成员变量)
void objc_registerClassPair(Class cls)
销毁一个类
void objc_disposeClassPair(Class cls)
获取isa指向的Class
Class object_getClass(id obj)
设置isa指向的Class
Class object_setClass(id obj, Class cls)
判断一个OC对象是否为Class
BOOL object_isClass(id obj)
判断一个Class是否为元类
BOOL class_isMetaClass(Class cls)
获取父类
Class class_getSuperclass(Class cls)
Runtime API - 02 – 成员变量
获取一个实例变量信息
Ivar class_getInstanceVariable(Class cls, const char *name)
拷贝实例变量列表(最后需要调用free释放)
Ivar *class_copyIvarList(Class cls, unsigned int *outCount)
设置和获取成员变量的值
void object_setIvar(id obj, Ivar ivar, id value)
id object_getIvar(id obj, Ivar ivar)
动态添加成员变量(已经注册的类是不能动态添加成员变量的)
BOOL class_addIvar(Class cls, const char * name, size_t size, uint8_t alignment, const char * types)
获取成员变量的相关信息
const char *ivar_getName(Ivar v)
const char *ivar_getTypeEncoding(Ivar v)
Runtime API - 03 – 属性
获取一个属性
objc_property_t class_getProperty(Class cls, const char *name)
拷贝属性列表(最后需要调用free释放)
objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
动态添加属性
BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes,
unsigned int attributeCount)
动态替换属性
void class_replaceProperty(Class cls, const char *name, const objc_property_attribute_t *attributes,
unsigned int attributeCount)
获取属性的一些信息
const char *property_getName(objc_property_t property)
const char *property_getAttributes(objc_property_t property)
Runtime API - 04 – 方法
获得一个实例方法、类方法
Method class_getInstanceMethod(Class cls, SEL name)
Method class_getClassMethod(Class cls, SEL name)
方法实现相关操作
IMP class_getMethodImplementation(Class cls, SEL name)
IMP method_setImplementation(Method m, IMP imp)
void method_exchangeImplementations(Method m1, Method m2)
拷贝方法列表(最后需要调用free释放)
Method *class_copyMethodList(Class cls, unsigned int *outCount)
动态添加方法
BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
动态替换方法
IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
获取方法的相关信息(带有copy的需要调用free去释放)
SEL method_getName(Method m)
IMP method_getImplementation(Method m)
const char *method_getTypeEncoding(Method m)
unsigned int method_getNumberOfArguments(Method m)
char *method_copyReturnType(Method m)
char *method_copyArgumentType(Method m, unsigned int index)
选择器相关
const char *sel_getName(SEL sel)
SEL sel_registerName(const char *str)
用block作为方法实现
IMP imp_implementationWithBlock(id block)
id imp_getBlock(IMP anImp)
BOOL imp_removeBlock(IMP anImp)
object_getClass(person)获取person的isa指向的对象。
NSLog(@"%p, %p, %p", object_getClass(person), [person class], [YZPerson class]);
结果: 0x1000025c0, 0x1000025c0, 0x1000025c0
这个很容易理解:
[YZPerson class],是class的类方法,返回的是self。
[person class]是class的对象方法,底层就是object_getClass(person)。
也就是person的isa指针指向的对象。所以,三个是指向同一块内存地址。
object_getClass([YZPerson class]),[YZPerson class]是YZPerson类对象。object_getClass([YZPerson class])是YZPerson类对象的isa指向的对象,是元类。
设置isa指向的Class
Class object_setClass(id obj, Class cls)
YZPerson *person = [[YZPerson alloc] init];
[person run];
object_setClass(person, [YZStudent class]);
[person run];
结果:
[YZPerson run]
[YZStudent run]
object_setClass(id obj, Class cls)可以将obj的isa指针指向cls。
动态创建一个类(参数:父类,类名,额外的内存空间)
Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)
举一个动态生成一个类的栗子:
void run()
{
NSLog(@"YZDog--run");
}
NSString *nameString = [NSString stringWithFormat:@"YZ%@", @"999"];
Class YZDog = objc_allocateClassPair([NSObject class], nameString.UTF8String, 0);//额外的内存空间一般为0即可
class_addIvar(YZDog, "_age", 4, 1, @encode(int));//动态添加一个成员变量
//参数意义:为哪个类添加成员变量,成员变量的名字,成员变量所占空间大小,成员变量内存对起方法,成员变量类型
class_addMethod(YZDog, @selector(run), (IMP)run, "v");//动态添加一个方法
//参数意义:为哪个类添加方法,方法的名字,方法的实现,方法的encode-type
objc_registerClassPair(YZDog);//需要注册一下
id dog = [[YZDog alloc] init];
[dog setValue:@"12" forKey:@"_age"];//kvo赋值
NSLog(@"%@", [dog valueForKey:@"_age"]);//kvo取值
objc_msgSend(dog, @selector(run));//调用dog的run方法
objc_disposeClassPair(YZDog);//在不需要的时候进行释放
结果:
12
YZDog--run
需要注意的是:
添加成员变量ivar的代码不能放在注册后面。
因为,注册等于就是class的结构已经确定,而确定后ivar就是只读的,不能再添加新的ivar。
这也就是说,我们不能为一个已经确定的类动态添加成员变量ivar
ivar 成员变量 = instance variable = 实例变量
property = 属性
method = 方法
获取一个实例变量信息
Ivar class_getInstanceVariable(Class cls, const char *name)
Ivar ageIvar = class_getInstanceVariable([YZPerson class], "_age");//获取类的成员变量,参数:哪个类的成员变量,成员变量的名字
NSLog(@"%s", ivar_getName(ageIvar));//获取成员变量的名字
结果:_age
Ivar nameIvar = class_getInstanceVariable([YZPerson class], "_name");//获取YZPerson下的_name成员变量
YZPerson *person = [[YZPerson alloc] init];
object_setIvar(person, nameIvar, @"jack");//设置person对象下的成员变量nameIvar的名字为jack
NSLog(@"%@", object_getIvar(person, nameIvar));//取出person对象下成员变量nameIvar的名字
结果:
jack
问:如何查看一个对象里面所有的成员变量?
unsigned int count;
Ivar *ivarList = class_copyIvarList([YZPerson class], &count);//获取成员变量列表,count是成员变量的数量
for (int i = 0; i
需要注意的是,ivarList是通过copy创建出来的,最后需要free一下
free(ivarList);
这个方法很有用,根据这个方法,可以找到iOS里面很多隐藏属性,然后通过KVC直接更改系统属性值。
Runtime遍历所有的属性或成员变量
利用KVC设置
就可以简单做字典转模型
YZPerson *person = [[YZPerson alloc] init];
Method runMethod = class_getInstanceMethod([YZPerson class], @selector(run));
Method warkMethod = class_getInstanceMethod([YZPerson class], @selector(walk));
method_exchangeImplementations(runMethod, warkMethod);//方法交换
[person run];
结果:
YZPerson--[YZPerson walk]
当我们为一个数组赋值上一个空值时,会造成崩溃,我们可以通过Runtime机制,减少这样的崩溃。
NSMutableArray *array = [NSMutableArray array];
[array addObject:@"123"];
[array addObject:nil];
报崩溃日志:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
可以看出,addObject:底部是调用了insertObject:方法,因此,报的是insertObject:相关错误。
我们创建一个NSMutableArray的分类NSMutableArray+Extension
并且
#import
@implementation NSMutableArray (Extension)
+ (void)load
{
Method method1 = class_getInstanceMethod(self, @selector(insertObject:atIndex:));
Method method2 = class_getInstanceMethod(self, @selector(yz_insertObject:atIndex:));
method_exchangeImplementations(method1, method2);
}
- (void)yz_insertObject:(id)anObject atIndex:(NSUInteger)index
{
if (anObject == nil) {
return;
}
}
@end
但是,你会发现,并没有交换成功
为什么呢?
这是因为,你看到的是NSMutableArray类型,其实isa指向的并不是NSMutableArray类型,通过报错可以看出其真正类型是__NSArrayM
这种,看着是NSMutableArray,实际是__NSArrayM类型的,被称为类簇,NSString,NSArray,NSDictionary这些都是类簇,真是类型都是其他类型。