What\'s the easiest way to create an array of structs in Cocoa?
If you want to use an NSArray you'll need to box up your structs. You can use the NSValue class to encode them.
Something like this to encode:
struct foo {
int bar;
};
struct foo foobar;
foobar.bar = 3;
NSValue *boxedFoobar = [NSValue valueWithBytes:&foobar objCType:@encode(struct foo)];
And then to get it back out:
struct foo newFoobar;
if (strcmp([boxedFoobar objCType], @encode(struct foo)) == 0)
[boxedFoobar getValue:&newFoobar];
Or dynamically allocating:
struct foo {
int bar;
};
int main (int argc, const char * argv[]) {
struct foo *foobar = malloc(sizeof(struct foo) * 3);
foobar[0].bar = 7; // or foobar->bar = 7;
free(foobar);
}
It is easier to use class, but what if you need to work with C and objective c structs like CGRect or others. I've tried to use NSValue,but it work strange...:
CGRect rect =CGRectMake(20,220,280,30);
NSValue* rectValue = [NSValue valueWithCGRect:rect];
NSArray *params1;
params1= [NSArray arrayWithObjects:rectValue,nil];
But,I can get CGRect value only as:
CGRect cgr = [[params1 objectAtIndex:0] CGRectValue];
When I use this:
id currentVal = [params1 objectAtIndex:0];
void* buffer;
buffer=[currentVal pointerValue];
it causes the error...
problem solved here
If you're okay with a regular old C array:
struct foo{
int bar;
};
int main (int argc, const char * argv[]) {
struct foo foobar[3];
foobar[0].bar = 7;
}
If you want an NSArray, you'll need a wrapper object. Most primitives use NSNumber, but that might not be applicable to your struct. A wrapper wouldn't be very hard to write, although that kind of defeats the purpose of using a struct!
Edit: This is something I haven't done but just thought of. If you think about it, an NSDictionary is basically a struct for objects. Your keys can be the names of the struct components as NSStrings and your values can be of the corresponding data type wrapped in the applicable Cocoa wrapper. Then just put these dictionaries in an NSArray.
I guess the gist is that you've got plenty of options. If I were you I'd do some experimenting and see what works best.
Does it need to be a struct? It's generally better to make it an object if you can. Then you can use things like KVC and Bindings with it.