01 类
什么是runtime?平时开发中有没有用过?
- OC是一门动态性比较强的编程语言,允许很多操作推迟到程序运行时再进行
OC的动态性就是由Runtime来支撑和实现的,Runtime是一套C语言的API,封装了很多动态性相关的函数
平时编写的OC代码,底层都是转换成了Runtime API进行调用- 具体应用
利用关联对象(AssociatedObject)给分类添加属性
遍历类的所有成员变量(修改textfield的占位文字颜色、字典转模型、自动归档解档)
交换方法实现(交换系统的方法)
利用消息转发机制解决方法找不到的异常问题
......
API
获取isa指向的Class
Class object_getClass(id obj)
动态创建一个类(参数:父类,类名,额外的内存空间)
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)
简单使用
// 创建类
Class newClass = objc_allocateClassPair([NSObject class], "Dog", 0);
class_addIvar(newClass, "_age", 4, 1, @encode(int));
class_addIvar(newClass, "_weight", 4, 1, @encode(int));
class_addMethod(newClass, (SEL)@"runGo", (IMP)runGo, "v@:");
// 注册类 ,添加成员属性一定要放在注册之前
//方法可以放在后面
objc_registerClassPair(newClass);
id per = [newClass new];
[per setValue:@18 forKey:@"age"];
[per setValue:@180 forKey:@"weight"];
NSLog(@"%@类型", per);
// 在不需要这个类时释放
objc_disposeClassPair(newClass);
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)
简单使用
Ivar ageIvar= class_getInstanceVariable([Person class], "_age");
NSLog(@"%s-%s", ivar_getName(ageIvar),ivar_getTypeEncoding(ageIvar));
//_age-@"NSString"
//设置和获取成员变量的值
Person *person = [Person new];
object_setIvar(person, ageIvar, @"120");
object_getIvar(person, ageIvar);
NSLog(@"%@", person.age);
成员变量02
获取所有的成员变量
Ivar *class_copyIvarList(Class cls, unsigned int *outCount)
int count;
Ivar *ivars = class_copyIvarList([Person class], &count);
for (int i = 0; i < count; i++)
{
Ivar currentIvar = ivars[i];
NSLog(@"%s-%s", ivar_getName(currentIvar),ivar_getTypeEncoding(currentIvar));
}
free(ivars);//runtime使用copy创建的要手动释放
访问成员变量的非常的有用
- 可以找到隐藏的空间更改他的属性,例如我们修改testfield的占位文字的时候,想要改颜色需要设置属性String,如果我们直接找到他的label设置,_placeholderLabel
UITextField *testF = [[UITextField alloc] init];
testF.placeholder = @"我是占位文字";//懒加载
[testF setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
成员变量03
为什么NSNumber能把int转成对象
(__bridge id )(void *)10
- 可以用来字典转模型
,有父类,传的数据个数少,字母大小写,有其他的模型
获取一个属性
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)
03方法01
获得一个实例方法、类方法
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)
交换方法的实现
为了防止多次执行最好加上dispatch_once
Method eatM = class_getInstanceMethod([Person class], @selector(eat));
Method sleepM = class_getInstanceMethod([Person class], @selector(sleep));
Person *p = [Person new];
method_exchangeImplementations(eatM, sleepM);
[p sleep];//person eat
方法02
j交换方法之后,调用就相反了,他的作用不是交换我们自己写的方法,它是用来交换别人写的,官方或者地方放框架写的方法
比如拦截按钮的点击事件。不是要覆盖他的实现,一旦拦截了之后,想要再调用以前的方式,就得在再调用我们自己写的方法了
@implementation UIButton (Exchange)
+ (void)load
{
Method myMethod = class_getInstanceMethod([self class], @selector(mySendAction:to:forEvent:));
Method sysMethod = class_getInstanceMethod([self class], @selector(sendAction:to:forEvent:));
method_exchangeImplementations(myMethod, sysMethod);
}
- (void)mySendAction:(SEL)action to:(nullable id)target forEvent:(nullable UIEvent *)event
{
NSLog(@"调用了我的方法");
[self mySendAction:action to:target forEvent:event];
}
@end
交换的本质,我们凭找方法是根据SEl= @selector(name)去寻找。一开始缓存中是没有的,首先取class 的rw_t.会找到Method 相当于method_t 它里面有 Sel name,IMP imp const , const char *types
一旦交换了实现相当将它们的imp交换过来
- 底层源码
void method_exchangeImplementations(Method m1, Method m2)
{
if (!m1 || !m2) return;
mutex_locker_t lock(runtimeLock);
IMP m1_imp = m1->imp;
m1->imp = m2->imp;
m2->imp = m1_imp;
// RR/AWZ updates are slow because class is unknown
// Cache updates are slow because class is unknown
// fixme build list of classes whose Methods are known externally?
flushCaches(nil);
adjustCustomFlagsForMethodChange(nil, m1);
adjustCustomFlagsForMethodChange(nil, m2);
}
方法03
hook就是给系统的方法添加一些我们自己的东西,
我们都知到数组,不能添加空的nil。我们可以给addObject的方法给hook掉,insert方法,两个方法底层都是insert方法。
但是直接交换不成功,交换的时候一定要找到他的真实的类型。错误显示出NSMutableArray的真实类型是__NSArrayM,这种类型我们曾为类簇,他们的真实类型是别的类型。__NSDictionaryI,__NSDictionaryM,
@implementation NSMutableArray (addNil)
+ (void)load
{
Class cls = NSClassFromString(@"__NSArrayM");
Method myMethod = class_getInstanceMethod(cls, @selector(myInsertObject:atIndex:));
Method sysMethod = class_getInstanceMethod(cls, @selector(insertObject:atIndex:));
method_exchangeImplementations(myMethod, sysMethod);
}
- (void)myInsertObject:(id)anObject atIndex:(NSUInteger)index
{
if (anObject == nil) return;
[self myInsertObject:anObject atIndex:index];
}
@end
[UIFont systemFontOfSize:14];// 可以设一个系数,所有的字体都有变化
总结
什么是Runtime?平时项目中有用过么?
OC是一门动态性比较强的编程语言,允许很多操作推迟到程序运行时再进行,动态添加方法,
OC的动态性就是由Runtime来支撑和实现的,Runtime是一套C语言的API,封装了很多动态性相关的函数
平时编写的OC代码,底层都是转换成了Runtime API进行调用
具体应用
利用关联对象(AssociatedObject)给分类添加属性
遍历类的所有成员变量(修改textfield的占位文字颜色、字典转模型、自动归档解档)
交换方法实现(交换系统的方法)
利用消息转发机制解决方法找不到的异常问题
网友评论