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

前端 未结 5 1804
执念已碎
执念已碎 2021-01-30 18:06

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

5条回答
  •  一整个雨季
    2021-01-30 19:05

    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.

提交回复
热议问题