NSValue仅仅存放的是地址
如何在数据结构中存入C 结构体数据
在使用cocos2d时候发现需要将CGPoint存入数组中,而数组接受的类型是 id。为了解决这个问题,下面使用NSDictionary作为演示。解决方案是使用 NSValue 进行转换,它有两个函数供使用,
1 valueWithPoint:转换CGPoint和NSPoint 为NSValue;
2 valueWithPointer:转换任何C数据结构为NSValue
这样就可以使用NSValue来代替C结构体数据 存入数据结构了。
相应的从NSValue中获取数据的函数分别是 pointValue 和 pointerValue。
具体的样例代码如下 :
复制代码
|
复制代码
|
复制代码
|
输出结果如下:
2011-12-15 02:09:53.261 TestNSValue[2157:903] Hello, World!
2011-12-15 02:09:53.267 TestNSValue[2157:903] point x = 1.000000, y = 2.000000
2011-12-15 02:09:53.268 TestNSValue[2157:903] point1 x = 3.000000, y = 4.000000
2011-12-15 02:09:53.268 TestNSValue[2157:903] point2 x = 0.000000, y = 0.000000
2011-12-15 02:09:53.269 TestNSValue[2157:903] point3 x = 7.000000, y = 8.000000
注意:point2 的数据是有问题的因为 point2的内存在test函数中已经释放了,这说明NSValue仅仅存放的是地址而已。
point1 是Test类的成员变量所以内存一直都在 数据是正确的。
point3 是使用malloc分配内存的 所以也是正确的,别忘记在main中free掉。