runtime简单使用

前言

在开始之前建议先阅读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);
### 如何在Android平台上使用ONNX Runtime 为了能够在Android设备上运行基于ONNX模型的应用程序,开发者通常会采用官方提供的预编译库文件来简化集成过程。对于希望利用ONNX Runtime执行推理操作的移动应用开发人员来说,可以按照如下方法完成环境搭建: #### 添加依赖项至项目配置 首先,在项目的`build.gradle`文件内加入必要的依赖声明以便引入ONNX Runtime支持包[^5]。 ```gradle dependencies { implementation 'ai.onnxruntime:onnxruntime-android:1.10.0' } ``` 此版本号需依据实际需求调整到最新稳定版。 #### 初始化并加载模型 接着通过Java/Kotlin代码实现对特定ONNX格式神经网络结构的实例化以及参数读取工作。下面给出了一段简单的示例用于说明如何创建Session对象来进行预测任务处理[^6]。 ```java import org.tensorflow.lite.support.image.TensorImage; // ... other imports ... OnnxTensor inputTensor = OnnxTensor.createTensor(env, inputData); Session session = new Session(assetFilePath); // assetFilePath指向本地存储中的onnx模型路径 session.run(inputTensor); ``` 需要注意的是这里假设已经准备好了一个适用于移动端部署的小型高效模型,并将其放置于应用程序资源目录下供后续调用。 #### 处理输入输出数据 最后一步就是针对具体的业务场景设计合理的接口函数负责接收原始传感器采集的数据作为算法运算前驱条件;同时解析返回的结果集进而驱动UI界面更新或其他逻辑控制流程[^7]。 ```kotlin val outputMap = mutableMapOf<String, Any>() for ((key, value) in result.outputNames()) { val tensorValue = result.getOutput(key) when (tensorValue.type()) { TensorProto.DataType.FLOAT -> { val floatArray = tensorValue.floatData().toFloatArray() outputMap[key] = floatArray } // Handle other data types... } } return outputMap ``` 上述代码片段展示了怎样获取由模型产生的各类数值信息并将它们转换成易于使用的Kotlin集合形式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值