美文网首页
Runtime(一)初识

Runtime(一)初识

作者: 炒河粉儿 | 来源:发表于2019-08-16 09:35 被阅读0次

基本概念

runtime是属于OC的底层,是一套比较底层的纯C语言API, 属于1个C语言库, 包含了很多底层的C语言API,可以进行一些非常底层的操作(用OC是无法现实的, 不好实现)。 在我们平时编写的OC代码中, 程序运行过程时, 其实最终都是转成了runtime的C语言代码, runtime算是OC的幕后工作者。

[Person alloc]init];

objc_msgSend(objc_msgSend("Person","alloc"),"init");

作用

  1. 在程序运行的过程中动态创建一个类,KVO的底层实现原理。
  2. 在程序运行过程中动态的添加属性和方法,分类中添加属性,消息转发和方法替换。
  3. 遍历成员变量,归解档,model和字典互相转换,MJExtension,YYModel.

头文件和常用函数

使用runtime时,导入头文件

#import <objc/runtime.h>
#import <objc/message.h>

获取类

Class PersonClass = object_getClass([Person class]);

SEL是selector在 Objc 中的表示:

SEL oriSEL = @selector(test1);

获取类方法

Method oriMethod = class_getClassMethod(Class cls , SEL name);

获取实例方法

Method oriMethod = class_getInstanceMethod(Class cls , SEL name);

添加方法

class_addMethod([self class], oriSEL, method_getImplementation(cusMethod), method_getTypeEncoding(cusMethod));

替换原方法

class_replaceMethod([self class], cusSEL, method_getImplementation(oriMethod), method_getTypeEncoding(oriMethod));

交换两个方法

method_exchangeImplementations(oriMethod, cusMethod);

获取一个类的属性列表,返回值是一个数组

unsigned int count = 0;
objc_property_t *propertyList = class_copyPropertyList([self class], &count);

获取一个类的方法列表

unsigned int count = 0;
Method *methodList = class_copyMethodList([self class], &count);

获取一个类的成员变量列表

Ivar *ivarList = class_copyIvarList([self class], &count);

获取成员变量的名字

const char *ivar_getName(Ivar v)

获取成员变量的类型

const char *ivar_getTypeEndcoding(Ivar v)

获取一个类的协议列表

__unsafe_unretained Protocol **protocolList = class_copyProtocolList([self class], &count);

set方法

void objc_setAssociatedObject(id object , const void *key ,id value ,objc_AssociationPolicy policy)

get方法

id objc_getAssociatedObject(id object , const void *key)

相关文章

网友评论

      本文标题:Runtime(一)初识

      本文链接:https://www.haomeiwen.com/subject/uaaxsctx.html