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

Fattie picture Fattie · Dec 23, 2010 · Viewed 26.5k times · Source

What's the usual way to store c-structures in an NSArray? Advantages, disadvantages, memory handling?

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

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

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

(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...

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 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.

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 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];

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

Answer

Justin Spahr-Summers picture Justin Spahr-Summers · Dec 23, 2010

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];