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

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

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

5条回答
  •  孤城傲影
    2021-01-30 18:45

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

提交回复
热议问题