Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...