Runtime的使用

Runtime的三种使用方式:

  • OC原生底层调用会间接使用runtime
    例如:方法的调用实质就是消息的发送
  • 调用NSObject的方法,间接调用runtime
    例如:
- (BOOL)isKindOfClass:(Class)aClass;
- (BOOL)isMemberOfClass:(Class)aClass;
- (BOOL)conformsToProtocol:(Protocol *)aProtocol;
- (BOOL)respondsToSelector:(SEL)aSelector;
  • 直接调用runtime api

Runtime 常用API

Working with Classes
//Returns the name of a class.
const char * class_getName(Class cls);

//Returns the superclass of a class.
//获取某类的父类
Class class_getSuperclass(Class cls);

//Returns a Boolean value that indicates whether a class object is a metaclass.
//是否为元类
BOOL class_isMetaClass(Class cls);

//Returns the size of instances of a class.
//获取类的实例大小
size_t class_getInstanceSize(Class cls);

//Returns the Ivar for a specified instance variable of a given class.
//获取实例变量
Ivar class_getInstanceVariable(Class cls, const char *name);

//Returns the Ivar for a specified class variable of a given class.
//获取类变量
Ivar class_getClassVariable(Class cls, const char *name);

//Adds a new instance variable to a class.
//为类添加实例变量
BOOL class_addIvar(Class cls, const char *name, size_t size, uint8_t alignment, const char *types);

//Describes the instance variables declared by a class.
//copy类的实例变量列表
Ivar  _Nonnull * class_copyIvarList(Class cls, unsigned int *outCount);

//Returns a property with a given name of a given class.
//获取某类的属性
objc_property_t class_getProperty(Class cls, const char *name);

//Describes the properties declared by a class.
//copy类的属性列表
objc_property_t  _Nonnull * class_copyPropertyList(Class cls, unsigned int *outCount);

//Adds a new method to a class with a given name and implementation.
//为类添加方法
BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types);

//Returns a specified instance method for a given class.
//获取实例方法
Method class_getInstanceMethod(Class cls, SEL name);

//Returns a pointer to the data structure describing a given class method for a given class.
//获取类方法
Method class_getClassMethod(Class cls, SEL name);

//Describes the instance methods implemented by a class.
//copy类的方法列表
Method  _Nonnull * class_copyMethodList(Class cls, unsigned int *outCount);

//Replaces the implementation of a method for a given class.
//替换类某方法的实现
IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types);

//Returns the function pointer that would be called if a particular message were sent to an instance of a class.
//获取方法的实现
IMP class_getMethodImplementation(Class cls, SEL name);

//Returns a Boolean value that indicates whether instances of a class respond to a particular selector.
//类是否实现某方法
BOOL class_respondsToSelector(Class cls, SEL sel);

//Adds a protocol to a class.
//为类遵循协议
BOOL class_addProtocol(Class cls, Protocol *protocol);

//Adds a property to a class.
BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount);

//Replace a property of a class.
void class_replaceProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount);

//Returns a Boolean value that indicates whether a class conforms to a given protocol.
//判断类是否遵循某协议
BOOL class_conformsToProtocol(Class cls, Protocol *protocol);

//Describes the protocols adopted by a class.
//copy类遵循的协议列表
Protocol * _Nonnull * class_copyProtocolList(Class cls, unsigned int *outCount);
Adding Classes
//Creates a new class and metaclass.
//分配空间,创建类(仅在创建后,注册前可以添加成员变量)
Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes);

//Destroys a class and its associated metaclass.
//注销类
void objc_disposeClassPair(Class cls);

//Registers a class that was allocated using objc_allocateClassPair.
//注册一个类(注册后可使用该类创建对象)
void objc_registerClassPair(Class cls);
Working with Instances
//Reads the value of an instance variable in an object.
//获取对象中功能实例变量的值
id object_getIvar(id obj, Ivar ivar);

//Sets the value of an instance variable in an object.
//设置对象中功能实例变量的值
void object_setIvar(id obj, Ivar ivar, id value);

//Returns the class name of a given object.
//获取对象的类名
const char * object_getClassName(id obj);

//Returns the class of an object.
//获取对象的Class
Class object_getClass(id obj);

//Sets the class of an object.
//设置对象的Class
Class object_setClass(id obj, Class cls);
Obtaining Class Definitions
//Obtains the list of registered class definitions.
int objc_getClassList(Class  _Nonnull *buffer, int bufferCount);

//Creates and returns a list of pointers to all registered class definitions.
Class  _Nonnull * objc_copyClassList(unsigned int *outCount);

//Returns the metaclass definition of a specified class.
//获取MetaClass对象
id objc_getMetaClass(const char *name);
Working with Instance Variables
//Returns the name of an instance variable.
//获取类名
const char * ivar_getName(Ivar v);

//Returns the type string of an instance variable.
const char * ivar_getTypeEncoding(Ivar v);
Associative References
//Sets an associated value for a given object using a given key and association policy.
//为实例对象关联对象
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);

//Returns the value associated with a given object for a given key.
//获取实例对象关联对象
id objc_getAssociatedObject(id object, const void *key);
Sending Messages
//Sends a message with a simple return value to an instance of a class.
//发送消息
void objc_msgSend(void);
Working with Methods
//Returns the name of a method.
//获取方法名
SEL method_getName(Method m);

//Returns the implementation of a method.
//获取方法实现
IMP method_getImplementation(Method m);

//Returns a string describing a method's parameter and return types.
//获取方法的类型编码
const char * method_getTypeEncoding(Method m);

//Returns a string describing a method's return type.
//copy方法的返回类型
char * method_copyReturnType(Method m);

//Returns a string describing a single parameter type of a method.
//copy方法的参数类型
char * method_copyArgumentType(Method m, unsigned int index);

//Returns by reference a string describing a method's return type.
//获取方法返回类型
void method_getReturnType(Method m, char *dst, size_t dst_len);

//Returns the number of arguments accepted by a method.
//获取方法参数个数
unsigned int method_getNumberOfArguments(Method m);

//Returns by reference a string describing a single parameter type of a method.
//获取方法参数的类型
void method_getArgumentType(Method m, unsigned int index, char *dst, size_t dst_len);

//Returns a method description structure for a specified method.
//获取方法的描述
struct objc_method_description * method_getDescription(Method m);

//Sets the implementation of a method.
//设置方法的实现
IMP method_setImplementation(Method m, IMP imp);

//Exchanges the implementations of two methods.
//替换方法的实现
void method_exchangeImplementations(Method m1, Method m2);
Working with Selectors
//Returns the name of the method specified by a given selector.
const char * sel_getName(SEL sel);

//Registers a method with the Objective-C runtime system, maps the method name to a selector, and returns the selector value.
SEL sel_registerName(const char *str);

//Returns a Boolean value that indicates whether two selectors are equal.
BOOL sel_isEqual(SEL lhs, SEL rhs);
Working with Protocols
//Returns a specified protocol.
//获取某个协议
Protocol * objc_getProtocol(const char *name);

//Returns an array of all the protocols known to the runtime.
//copy运行时注册过的协议列表
Protocol * _Nonnull * objc_copyProtocolList(unsigned int *outCount);

//Creates a new protocol instance.
//分配空间创建协议
Protocol * objc_allocateProtocol(const char *name);

//Registers a newly created protocol with the Objective-C runtime.
//注册一个协议
void objc_registerProtocol(Protocol *proto);

//Adds a registered protocol to another protocol that is under construction.
void protocol_addProtocol(Protocol *proto, Protocol *addition);

//Adds a property to a protocol that is under construction.
void protocol_addProperty(Protocol *proto, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount, BOOL isRequiredProperty, BOOL isInstanceProperty);

//Returns a the name of a protocol.
const char * protocol_getName(Protocol *proto);

//Returns a Boolean value that indicates whether two protocols are equal.
//判断两个协议是否一致
BOOL protocol_isEqual(Protocol *proto, Protocol *other);

//Returns an array of the properties declared by a protocol.
//copy协议的属性列表
objc_property_t  _Nonnull * protocol_copyPropertyList(Protocol *proto, unsigned int *outCount);

//Returns the specified property of a given protocol.
//获取协议中的某个属性
objc_property_t protocol_getProperty(Protocol *proto, const char *name, BOOL isRequiredProperty, BOOL isInstanceProperty);

//Returns an array of the protocols adopted by a protocol.
//copy某协议所遵循的协议列表
Protocol * _Nonnull * protocol_copyProtocolList(Protocol *proto, unsigned int *outCount);

//Returns a Boolean value that indicates whether one protocol conforms to another protocol.
//判断一个协议是否遵循另一个协议
BOOL protocol_conformsToProtocol(Protocol *proto, Protocol *other);
Working with Properties
//Returns the name of a property.
//获取属性名
const char * property_getName(objc_property_t property);

//Returns the attribute string of a property.
//获取属性列表
const char * property_getAttributes(objc_property_t property);

//Returns the value of a property attribute given the attribute name.
//copy属性值
char * property_copyAttributeValue(objc_property_t property, const char *attributeName);

//Returns an array of property attributes for a given property.
//copy属性表
objc_property_attribute_t * property_copyAttributeList(objc_property_t property, unsigned int *outCount);

常用API的使用

动态创建类

void eat(){
    printf("animal eat");
}
- (void)dynamicClass {
    //动态创建类
    Class Animal = objc_allocateClassPair([NSObject class], "Animal", 0);
    //添加实例变量
    NSString *name = @"name";
    class_addIvar(Animal, name.UTF8String, sizeof(id), log2(sizeof(id)), @encode(id));
    //添加方法
    class_addMethod(Animal, @selector(eat), (IMP)eat, "v@:");
    //注册类
    objc_registerClassPair(Animal);
    
    id dog = [[Animal alloc]init];
    [dog setValue:@"Dog" forKey:name];
    NSLog(@"name:%@", [dog valueForKey:name]);
    
    [dog performSelector:@selector(eat)];
}

获取属性列表

- (void)getClassInfo {
    //获取成员变量列表
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([LPerson class], &count);
    for (int i = 0; i < count; i++) {
        Ivar var = ivars[i];
        const char *name = ivar_getName(var);
        NSString *key = [NSString stringWithUTF8String:name];
        NSLog(@"key:%@",key);
    }
    free(ivars);
}

生活如此美好,今天就点到为止。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355

推荐阅读更多精彩内容