【问题标题】:Use Struct with NSMutableArray [duplicate]将 Struct 与 NSMutableArray 一起使用
【发布时间】:2013-01-12 04:58:26
【问题描述】:

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

如何在 NSMutableArray 中使用 struct?

【问题讨论】:

  • 您可以创建一个 NSObject 子类,它本质上是一个结构体,并使用该子类。
  • 我不想使用 NSObject
  • 你为什么不想使用NSObject

标签: ios objective-c xcode


【解决方案1】:

你不能。 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);

顺便说一句,没有真正的理由为什么一个结构是堆分配的,一个堆栈分配的。只是想我会这样做以表明它有效。

【讨论】:

  • @OneManCrew 是正确的。您可以将其包装在 NSValue 中。
  • 是的,你可以使用NSValue
猜你喜欢
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多