当前位置: 移动技术网 > 移动技术>移动开发>IOS > runtime获取属性和成员变量方法

runtime获取属性和成员变量方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

成员变量

1、成员变量的定义

ivar: 实例变量类型,是一个指向objc_ivar结构体的指针
typedef struct objc_ivar *ivar;

2、相关函数

// 获取所有成员变量
class_copyivarlist
// 获取成员变量名
ivar_getname
// 获取成员变量类型编码
ivar_gettypeencoding
// 获取指定名称的成员变量
class_getinstancevariable
// 获取某个对象成员变量的值
object_getivar
// 设置某个对象成员变量的值
object_setivar

说明:

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

属性类型 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、实例应用

<!--person.h文件-->
@interface person : nsobject
{
  nsstring *address;
}
@property(nonatomic,strong)nsstring *name;
@property(nonatomic,assign)nsinteger age;
//遍历获取person类所有的成员变量ivarlist
- (void) getallivarlist {
  unsigned int methodcount = 0;
  ivar * ivars = class_copyivarlist([person class], &methodcount);
  for (unsigned int i = 0; i < methodcount; i ++) {
    ivar ivar = ivars[i];
    const char * name = ivar_getname(ivar);
    const char * type = ivar_gettypeencoding(ivar);
    nslog(@"person拥有的成员变量的类型为%s,名字为 %s ",type, name);
  }
  free(ivars);
}
<!--打印结果-->
2016-06-15 20:26:39.412 demo-cocoa之method swizzle[17798:2565569] person拥有的成员变量的类型为@"nsstring",名字为 address 
2016-06-15 20:26:39.413 demo-cocoa之method swizzle[17798:2565569] person拥有的成员变量的类型为@"nsstring",名字为 _name 
2016-06-15 20:26:39.413 demo-cocoa之method swizzle[17798:2565569] person拥有的成员变量的类型为q,名字为 _age

属性

1、属性的定义

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

2、相关函数

// 获取所有属性
class_copypropertylist
说明:使用class_copypropertylist并不会获取无@property声明的成员变量
// 获取属性名
property_getname
// 获取属性特性描述字符串
property_getattributes
// 获取所有属性特性
property_copyattributelist

3、实例应用

<!--person.h文件-->
@interface person : nsobject
{
  nsstring *address;
}
@property(nonatomic,strong)nsstring *name;
@property(nonatomic,assign)nsinteger age;
//遍历获取所有属性property
- (void) getallproperty {
  unsigned int propertycount = 0;
  objc_property_t *propertylist = class_copypropertylist([person class], &propertycount);
  for (unsigned int i = 0; i < propertycount; i++ ) {
    objc_property_t *thisproperty = propertylist[i];
    const char* propertyname = property_getname(*thisproperty);
    nslog(@"person拥有的属性为: '%s'", propertyname);
  }
}
<!--打印结果-->
2016-06-15 20:25:19.653 demo-cocoa之method swizzle[17778:2564081] person拥有的属性为: 'name'
2016-06-15 20:25:19.653 demo-cocoa之method swizzle[17778:2564081] person拥有的属性为: 'age'

应用具体场景

1、json到model的转化

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

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

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

- (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的基类中重写方法:

- (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来获取它的值。

方法:

ivar ivar = class_getinstancevariable([model class], "_str1");
nsstring * str1 = object_getivar(model, ivar);

写给看客

对于已入行的程序员来说,刨根问底,挖开底层是突破瓶颈的必经之路。要想要从技术开发的普通工人变成真正的工程师,就必须需要啃下这块骨头。

而且在完成这篇文章的过程中,我发现自己之前走了不少弯路。因为底层理解不够,在扩展学习时深感效率低下,过目即忘。归根结底是只了解皮毛,无法内化,深入理解开发者的思路。

当然文章也多是个人理解,如有错误也请留言指正,共同成长。感谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网