问题描述
在 NSArray
中存储c结构的常用方法是什么?优点,缺点,内存处理?
What's the usual way to store c-structures in an NSArray
? Advantages, disadvantages, memory handling?
值得注意的是, valueWithBytes
和 valueWithPointer
Notably, what's the difference between valueWithBytes
and valueWithPointer
-- raised by justin and catfish below.
到苹果讨论的 valueWithBytes:objCType: / code>为未来的读者...
Here's a link to Apple's discussion of valueWithBytes:objCType:
for future readers...
对于一些横向思维和更多的性能,Evgen提出了使用
For some lateral thinking and looking more at performance, Evgen has raised the issue of using STL::vector
in C++.
(这引发了一个有趣的问题:是否有快速c库,不像 STL :: vector
,但是要轻得多,允许最小的整齐处理数组...?)
(That raises an interesting issue: is there a fast c library, not unlike STL::vector
but much much lighter, that allows for the minimal "tidy handling of arrays" ...?)
所以原来的问题...
So the original question...
例如:
typedef struct _Megapoint {
float w,x,y,z;
} Megapoint;
所以:什么是正常的,最好的,惯用的方式来存储自己的结构, c $ c> NSArray ,以及如何处理该成语中的内存?
So: what's the normal, best, idiomatic way to store one's own structure like that in an NSArray
, and how do you handle memory in that idiom?
请注意,我专门寻找常用的成语存储结构。当然,通过做一个新的小类可以避免这个问题。然而,我想知道如何通常的成语,实际上将结构体放在数组中,感谢。
Please note that I am specifically looking for the usual idiom to store structs. Of course, one could avoid the issue by making a new little class. However I want to know how the usual idiom for actually putting structs in an array, thanks.
这里的NSData方法可能是?不是最好的...
BTW here's the NSData approach which is perhaps? not best...
Megapoint p;
NSArray *a = [NSArray arrayWithObjects:
[NSData dataWithBytes:&p length:sizeof(Megapoint)],
[NSData dataWithBytes:&p length:sizeof(Megapoint)],
[NSData dataWithBytes:&p length:sizeof(Megapoint)],
nil];
BTW作为参考,感谢Jarret Hardie,下面介绍如何存储 CGPoints
和 NSArray
中类似:
BTW as a point of reference and thanks to Jarret Hardie, here's how to store CGPoints
and similar in an NSArray
:
NSArray *points = [NSArray arrayWithObjects:
[NSValue valueWithCGPoint:CGPointMake(6.9, 6.9)],
[NSValue valueWithCGPoint:CGPointMake(6.9, 6.9)],
nil];
(请参阅不仅支持CoreGraphics结构 - 你也可以使用它。我建议这样做,因为类可能比 NSData
更轻的重量为简单的数据结构。
NSValue doesn't only support CoreGraphics structures – you can use it for your own too. I would recommend doing so, as the class is probably lighter weight than NSData
for simple data structures.
一个表达式如下:
[NSValue valueWithBytes:&p objCType:@encode(Megapoint)];
重新输入值:
Megapoint p;
[value getValue:&p];
这篇关于在NSArray中放置c-struct的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!