What's the easiest way to create an array of structs in Cocoa?
Create an Array of struct Using the malloc() Function in C The memory can be allocated using the malloc() function for an array of struct . This is called dynamic memory allocation. The malloc() (memory allocation) function is used to dynamically allocate a single block of memory with the specified size.
@interface Foo : NSObject { NSString *name; NSArray *books; } @end A->name = @"Clancy, Thomas"; A->books = [[NSArray alloc] initWithObjects:@"Book 1" @"Book2",nil]; self. authors = [[NSArray alloc] initWithObjects:A, nil];
A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With