iPhone开发:使用NSValue存储任意类型的数据

为了说明问题,我们定义2个结构AA,BB。

typedef struct _AA{

NSString *nameA;

}AA;

typedef struct _BB{

int k;

float m;

NSString *nameB;

AA aa;

}BB;

(BB有一个AA类型的成员aa)

初始化一个结构体数组

BB f[2] = {

{10,0.5f,@"bright",{@"a1"}},

{5,0.3f,@"mtf",{@"a2"}}

};

用encode编译器指令可以接受数据类型的名称并为你生成合适的字符串,并将value1,value2存入NSArray中

NSValue *value1 = [NSValue valueWithBytes:&f[0] objCType: @encode(BB)];

NSValue *value2 = [NSValue valueWithBytes:&f[1] objCType: @encode(BB)];

NSArray *array = [NSArray arrayWithObjects:value1,value2,nil];

从数组中取值

BB c;

for (NSValue *aValue in array) {

NSLog(@"%@",aValue);

[aValue getValue:&c];

NSLog(@"%d",c.k);

NSLog(@"%f",c.m);

NSLog(@"%@",c.nameB);

NSLog(@"%@",c.aa.nameA);

}

输出结果如下

2010-06-08 15:34:10.640 testValue[4240:207] <0a000000 0000003f 64300000 74300000>

2010-06-08 15:34:10.641 testValue[4240:207] 10

2010-06-08 15:34:10.642 testValue[4240:207] 0.500000

2010-06-08 15:34:10.643 testValue[4240:207] bright

2010-06-08 15:34:10.644 testValue[4240:207] a1

2010-06-08 15:34:10.644 testValue[4240:207] <05000000 9a99993e 84300000 94300000>

2010-06-08 15:34:10.645 testValue[4240:207] 5

2010-06-08 15:34:10.645 testValue[4240:207] 0.300000

2010-06-08 15:34:10.646 testValue[4240:207] mtf

2010-06-08 15:34:10.646 testValue[4240:207] a2

原文地址:https://www.cnblogs.com/javawebsoa/p/2458483.html