Joe Blow Joe Blow - 1 year ago 80
Objective-C Question

What's the best way to put a c-struct in an NSArray?

What's the usual way to store c-structures in an

? Advantages, disadvantages, memory handling?

Notably, what's the difference between
-- raised by justin and catfish below.

Here's a link to Apple's discussion of
for future readers...

For some lateral thinking and looking more at performance, Evgen has raised the issue of using
in C++.

(That raises an interesting issue: is there a fast c library, not unlike
but much much lighter, that allows for the minimal "tidy handling of arrays" ...?)

So the original question...

For example:

typedef struct _Megapoint {
float w,x,y,z;
} Megapoint;

So: what's the normal, best, idiomatic way to store one's own structure like that in an
, 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.

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)],

BTW as a point of reference and thanks to Jarret Hardie, here's how to store
and similar in an

NSArray *points = [NSArray arrayWithObjects:
[NSValue valueWithCGPoint:CGPointMake(6.9, 6.9)],
[NSValue valueWithCGPoint:CGPointMake(6.9, 6.9)],

(see How can I add CGPoint objects to an NSArray the easy way?)

Answer Source

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.

Simply use an expression like the following:

[NSValue valueWithBytes:&p objCType:@encode(Megapoint)];

And to get the value back out:

Megapoint p;
[value getValue:&p];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download