runtime简单使用

来源:互联网 发布:wegame 知乎 编辑:程序博客网 时间:2024/05/17 06:22

前言

在开始之前建议先阅读iOS runtime的基础理解篇:iOS内功篇:runtime

有筒子在面试的时候,遇到这样一个问题:“你知道成员变量的本质是什么吗?”,筒子立马懵逼了,成员变量的本质?成员变量就是成员变量啊,平时只管用,还有什么更深层的含义?本文着重介绍runtime中成员变量和属性的定义和使用。

名词解析

成员变量

1、定义:

Ivar: 实例变量类型,是一个指向objc_ivar结构体的指针

1
typedef struct objc_ivar *Ivar;

2、操作函数:

1
2
// 获取所有成员变量
class_copyIvarList
1
2
// 获取成员变量名
ivar_getName
1
2
// 获取成员变量类型编码
ivar_getTypeEncoding
1
2
// 获取指定名称的成员变量
class_getInstanceVariable
1
2
// 获取某个对象成员变量的值
object_getIvar
1
2
// 设置某个对象成员变量的值
object_setIvar

3、使用实例:

Model的头文件声明如下:

1
2
3
4
5
6
@interface Model : NSObject {
        NSString * _str1;
    }
    @property NSString * str2;
    @property (nonatomic, copy) NSDictionary * dict1;
    @end

获取其成员变量:

1
2
3
4
5
6
7
8
9
unsigned int outCount = 0;
Ivar * ivars = class_copyIvarList([Model class], &outCount);
for (unsigned int i = 0; i < outCount; i ++) {
   Ivar ivar = ivars[i];
   const char * name = ivar_getName(ivar);
   const char * type = ivar_getTypeEncoding(ivar);
   NSLog(@"类型为 %s 的 %s ",type, name);
}
free(ivars);

打印结果:

1
2
3
runtimeIvar[602:16885] 类型为 @"NSString" 的 _str1 
runtimeIvar[602:16885] 类型为 @"NSString" 的 _str2 
runtimeIvar[602:16885] 类型为 @"NSDictionary" 的 _dict1

属性

1、定义:

objc_property_t:声明的属性的类型,是一个指向objc_property结构体的指针

1
typedef struct objc_property *objc_property_t;

2、操作函数:

1
2
// 获取所有属性
class_copyPropertyList

说明:使用class_copyPropertyList并不会获取无@property声明的成员变量

1
2
// 获取属性名
property_getName
1
2
// 获取属性特性描述字符串
property_getAttributes
1
2
// 获取所有属性特性
property_copyAttributeList

说明:

property_getAttributes函数返回objc_property_attribute_t结构体列表,objc_property_attribute_t结构体包含name和value,常用的属性如下:

1
2
3
4
属性类型  name值:T  value:变化
编码类型  name值:C(copy) &(strong) W(weak) 空(assign) 等 value:无
非/原子性 name值:空(atomic) N(Nonatomic)  value:无
变量名称  name值:V  value:变化

使用property_getAttributes获得的描述是property_copyAttributeList能获取到的所有的name和value的总体描述,如 T@"NSDictionary",C,N,V_dict1

3、使用实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
unsigned int outCount = 0;
    objc_property_t * properties = class_copyPropertyList([Model class], &outCount);
    for (unsigned int i = 0; i < outCount; i ++) {
        objc_property_t property = properties[i];
        //属性名
        const char * name = property_getName(property);
        //属性描述
        const char * propertyAttr = property_getAttributes(property);
        NSLog(@"属性描述为 %s 的 %s ", propertyAttr, name);
         
        //属性的特性
        unsigned int attrCount = 0;
        objc_property_attribute_t * attrs = property_copyAttributeList(property, &attrCount);
        for (unsigned int j = 0; j < attrCount; j ++) {
            objc_property_attribute_t attr = attrs[j];
            const char * name = attr.name;
            const char * value = attr.value;
            NSLog(@"属性的描述:%s 值:%s", name, value);
        }
        free(attrs);
        NSLog(@"\n");
    }
    free(properties);

打印结果:

1
2
3
4
5
6
7
8
9
10
11
runtimeIvar[661:27041] 属性描述为 T@"NSString",&,V_str2 的 str2 
runtimeIvar[661:27041] 属性的描述:T 值:@"NSString"
runtimeIvar[661:27041] 属性的描述:& 值:
runtimeIvar[661:27041] 属性的描述:V 值:_str2
runtimeIvar[661:27041] 
runtimeIvar[661:27041] 属性描述为 T@"NSDictionary",C,N,V_dict1 的 dict1 
runtimeIvar[661:27041] 属性的描述:T 值:@"NSDictionary"
runtimeIvar[661:27041] 属性的描述:C 值:
runtimeIvar[661:27041] 属性的描述:N 值:
runtimeIvar[661:27041] 属性的描述:V 值:_dict1
runtimeIvar[661:27041]

应用实例

1、Json到Model的转化

在开发中相信最常用的就是接口数据需要转化成Model了(当然如果你是直接从Dict取值的话。。。),很多开发者也都使用著名的第三方库如JsonModel、Mantle或MJExtension等,如果只用而不知其所以然,那真和“搬砖”没啥区别了,下面我们使用runtime去解析json来给Model赋值。

原理描述:用runtime提供的函数遍历Model自身所有属性,如果属性在json中有对应的值,则将其赋值。

核心方法:在NSObject的分类中添加方法:

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
30
31
32
33
34
- (instancetype)initWithDict:(NSDictionary *)dict {
 
    if (self = [self init]) {
        //(1)获取类的属性及属性对应的类型
        NSMutableArray * keys = [NSMutableArray array];
        NSMutableArray * attributes = [NSMutableArray array];
        /*
         * 例子
         * name = value3 attribute = T@"NSString",C,N,V_value3
         * name = value4 attribute = T^i,N,V_value4
         */
        unsigned int outCount;
        objc_property_t * properties = class_copyPropertyList([self class], &outCount);
        for (int i = 0; i < outCount; i ++) {
            objc_property_t property = properties[i];
            //通过property_getName函数获得属性的名字
            NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            [keys addObject:propertyName];
            //通过property_getAttributes函数可以获得属性的名字和@encode编码
            NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
            [attributes addObject:propertyAttribute];
        }
        //立即释放properties指向的内存
        free(properties);
 
        //(2)根据类型给属性赋值
        for (NSString * key in keys) {
            if ([dict valueForKey:key] == nil) continue;
            [self setValue:[dict valueForKey:key] forKey:key];
        }
    }
    return self;
 
}

读者可以进一步思考:

  • 如何识别基本数据类型的属性并处理

  • 空(nil,null)值的处理

  • json中嵌套json(Dict或Array)的处理

尝试解决以上问题,你也能写出属于自己的功能完备的Json转Model库。

2、快速归档

有时候我们要对一些信息进行归档,如用户信息类UserInfo,这将需要重写initWithCoder和encodeWithCoder方法,并对每个属性进行encode和decode操作。那么问题来了:当属性只有几个的时候可以轻松写完,如果有几十个属性呢?那不得写到天荒地老?。。。

原理描述:用runtime提供的函数遍历Model自身所有属性,并对属性进行encode和decode操作。

核心方法:在Model的基类中重写方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        unsigned int outCount;
        Ivar * ivars = class_copyIvarList([self class], &outCount);
        for (int i = 0; i < outCount; i ++) {
            Ivar ivar = ivars[i];
            NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
        }
    }
    return self;
}
 
- (void)encodeWithCoder:(NSCoder *)aCoder {
    unsigned int outCount;
    Ivar * ivars = class_copyIvarList([self class], &outCount);
    for (int i = 0; i < outCount; i ++) {
        Ivar ivar = ivars[i];
        NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
}

3、访问私有变量

我们知道,OC中没有真正意义上的私有变量和方法,要让成员变量私有,要放在m文件中声明,不对外暴露。如果我们知道这个成员变量的名称,可以通过runtime获取成员变量,再通过getIvar来获取它的值。

方法:

1
2
Ivar ivar = class_getInstanceVariable([Model class], "_str1");
NSString * str1 = object_getIvar(model, ivar);
原创粉丝点击