runtime运行时机制 (一)

一、思维导图

二、关键字解释

1
2
3
4
5
6
7
8
(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、获取实例变量,动态改变对象属性的值

1
2
3
4
5
6
7
8
9
10
11
12
#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、获取类对象的所有属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
+ (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、简单的字典转模型

1
2
3
4
5
6
7
8
9
10
+ (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、交换方法(未完待续)

posted @   TheYouth  阅读(156)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2016-03-09 数组与指针(数组中所有元素的和)
点击右上角即可分享
微信分享提示