runtime运行时机制 (一)

一、思维导图

二、关键字解释

   (1)调用运行时方法
    1、Iva成员变量    class_copyIvarList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)
    2、Method 方法   class_copyMethodList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)
    3、property 属性  class_copyMethodList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)
    4、Protocol 协议  class_copyProtocolList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)
     (2)注意事项
    1、注意内存的释放,因为是c语言,需要手动管理内存,free(运行时数组)
     

三、实例

1、获取实例变量,动态改变对象属性的值

#import <objc/runtime.h>
  //  通过运行时来遍历每个变量
    unsigned int count;
    //class_copyIvarList 获取所有实例变量数组
    Ivar *varList = class_copyIvarList([UITextField class],&count);
      for (NSInteger i = 0; i < count; i++) {
        Ivar var = varList[i];
        //遍历所有实例变量的名字
        NSLog(@"%s",ivar_getName(var));
    }
    //因为是c语言,需要自已管理内存,所以这里需要释放
    free(varList);

 2、获取类对象的所有属性

+ (NSArray *)xzr_propertys{
    NSMutableArray *propertys = [NSMutableArray array];
     /**从关联对象中获取属性,如果有直接返回
      这样做会节省资源,更快的返回,只算一次*/
    NSArray *ptyList = objc_getAssociatedObject(self, propertyListKey);
    if (ptyList != nil) {
        return ptyList;
    }
    unsigned int count = 0;
   /**调用运行时方法
    1、Iva成员变量    
    2、Method 方法   
    3、property 属性  
    4、Protocol 协议  
   */
    objc_property_t * propertyList =class_copyPropertyList([self class], &count);
    for (unsigned int i =0; i<count; i++) {
        const char *charProperty = property_getName(propertyList[i]);
        [propertys addObject:[NSString stringWithCString:charProperty encoding:NSUTF8StringEncoding]];
    }
    free(propertyList);
    /**对象的属性数组已经完毕,利用关联对象,动态添加属性
     1、对象self [在OC中 class 也是一上特殊的对象]
     2、动态获取key,获取值的时候使用
     3、动态添加属性
     4、对象引用关系
     */
    objc_setAssociatedObject(self,propertyListKey,propertys.mutableCopy, OBJC_ASSOCIATION_COPY_NONATOMIC);
    return propertys;

 3、简单的字典转模型

+ (instancetype)xzr_objectWithDic:(NSDictionary *)dic{
    id object = [[self alloc] init];
    NSArray *keys = [self xzr_propertys];
    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([keys containsObject:key]) {
            [object setValue:obj forKey:key];
        }
    }];
    return object;
}

 4、交换方法(未完待续)

将来的自己,会感谢现在不放弃的自己!
原文地址:https://www.cnblogs.com/TheYouth/p/6528167.html