iOS runtime实战应用:成员变量和属性

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

[[164431]]

原文

前言

在开始之前建议先阅读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. class_getInstanceVariable 
  1. // 获取成员变量类型编码 
  2. ivar_getTypeEncoding 
  1. // 设置某个对象成员变量的值 
  2. object_setIvar 
  1. // 获取某个对象成员变量的值 
  2. object_getIvar 

3、使用实例:

Model的头文件声明如下:

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

获取其成员变量:

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

打印结果:

  1. runtimeIvar[602:16885] 类型为 @"NSString" 的 _str1  
  2. runtimeIvar[602:16885] 类型为 @"NSString" 的 _str2  
  3. 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_getAttributes 
  1. // 获取属性名 
  2. property_getName 
  1. // 获取所有属性特性 
  2. property_copyAttributeList 

说明:

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

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

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

3、使用实例:

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

打印结果:

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

应用实例

1、Json到Model的转化

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

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

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

  1. - (instancetype)initWithDict:(NSDictionary *)dict { 
  2.   
  3.     if (self = [self init]) { 
  4.         //(1)获取类的属性及属性对应的类型 
  5.         NSMutableArray * keys = [NSMutableArray array]; 
  6.         NSMutableArray * attributes = [NSMutableArray array]; 
  7.         /* 
  8.          * 例子 
  9.          * name = value3 attribute = T@"NSString",C,N,V_value3 
  10.          * name = value4 attribute = T^i,N,V_value4 
  11.          */ 
  12.         unsigned int outCount; 
  13.         objc_property_t * properties = class_copyPropertyList([self class], &outCount); 
  14.         for (int i = 0; i < outCount; i ++) { 
  15.             objc_property_t property = properties[i]; 
  16.             //通过property_getName函数获得属性的名字 
  17.             NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; 
  18.             [keys addObject:propertyName]; 
  19.             //通过property_getAttributes函数可以获得属性的名字和@encode编码 
  20.             NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding]; 
  21.             [attributes addObject:propertyAttribute]; 
  22.         } 
  23.         //立即释放properties指向的内存 
  24.         free(properties); 
  25.   
  26.         //(2)根据类型给属性赋值 
  27.         for (NSString * key in keys) { 
  28.             if ([dict valueForKey:key] == nil) continue
  29.             [self setValue:[dict valueForKey:key] forKey:key]; 
  30.         } 
  31.     } 
  32.     return self; 
  33.   

读者可以进一步思考:

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

  • 空(nil,null)值的处理

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

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

2、快速归档

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

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

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

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

3、访问私有变量

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

方法:

  1. Ivar ivar = class_getInstanceVariable([Model class], "_str1"); 
  2. NSString * str1 = object_getIvar(model, ivar); 

欢迎大家交流探讨。

责任编辑:倪明 来源: 明仔Su的简书
相关推荐

2012-05-14 17:06:46

iOS

2012-04-09 13:43:12

Java

2014-04-01 10:50:42

iOS开发runtimeObjective-C

2015-08-07 09:33:24

RuntimeModel

2011-08-02 18:30:32

iOS 应用程序 属性

2010-03-17 16:54:10

Java sum传递

2020-06-19 09:15:11

Python内置方法属性应用

2011-09-16 17:12:01

iOS应用Android应用Ribblet

2013-12-26 09:27:51

AndroidiOS调查数据

2018-08-09 20:47:41

2014-03-07 09:41:20

AndroidiOS恶意应用

2011-09-19 10:24:58

苹果iOS谷歌

2017-04-11 08:36:09

iOS编译应用

2010-08-31 15:24:43

CSSpositionabsolute

2021-04-20 08:31:59

应用监控高可用

2018-11-07 09:39:03

Runtime开发项目

2010-01-18 14:54:00

VB.NET共享成员变

2009-11-12 11:18:28

VS Ribbon界面

2011-08-05 16:41:48

iOS 队列 内存

2010-08-19 13:43:07

marginpadding
点赞
收藏

51CTO技术栈公众号