1

Possible Duplicate:
What’s the best way to put a c-struct in an NSArray?

How can I use struct inside NSMutableArray?

Community
  • 1
  • 1
One Man Crew
  • 9,420
  • 2
  • 42
  • 51

1 Answers1

2

You can't. All of the collections in Foundation can store only Objective-C objects. Since a struct is not an Objective-C object, it cannot be stored in there.

But you could wrap your struct into a simple NSObject subclass and store that in the array.

Or with NSValue:

#import <Foundation/Foundation.h>

struct TestStruct {
    int a;
    float b;
};

...

NSMutableArray *theArray = [NSMutableArray new];    

...

struct TestStruct *testStructIn = malloc(sizeof(struct TestStruct));
testStructIn->a = 10;
testStructIn->b = 3.14159;

NSValue *value = [NSValue valueWithBytes:testStructIn objCType:@encode(struct TestStruct)];
[theArray addObject:value];

free(testStructIn);

...

struct TestStruct testStructOut;
NSValue *value = [theArray objectAtIndex:0];
[value getValue:&testStructOut];

NSLog(@"a = %i, b = %.5f", testStructOut.a, testStructOut.b);

No real reason why one struct is heap allocated and one stack allocated, by the way. Just thought I'd do that to show it working.

mattjgalloway
  • 34,792
  • 12
  • 100
  • 110