使用Struct与NSMutableArray

时间:2013-01-28 18:54:23

标签: ios objective-c xcode

  

可能重复:
  What’s the best way to put a c-struct in an NSArray?

如何在NSMutableArray中使用struct?

1 个答案:

答案 0 :(得分:2)

你做不到。 Foundation中的所有集合只能存储Objective-C对象。由于struct不是Objective-C对象,因此无法存储在那里。

但是你可以将struct包装成一个简单的NSObject子类并将其存储在数组中。

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

顺便说一句,没有一个真正的原因可以解决为什么一个结构分配堆和一个堆栈分配。我以为我会这样做才能证明它有效。