views:

2688

answers:

4

What's the easiest way to create an array of structs in Cocoa?

+1  A: 

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.

Rich Catalano
+7  A: 

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);
}
Georg
thanks gs. I'm divided between your answer and ashley's, but I ended up going for ashley's answer for popularity, and because it uses NS(Mutable)Array, which is far more flexible. But if I could select two answers, I would.
Steph Thirion
+10  A: 

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];
Ashley Clark
A: 

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.

Peter Hosey
Hey Peter, right now I don't think I need those, but still that's a topic I'm interested in. I just opened a specific question: http://stackoverflow.com/questions/393662
Steph Thirion