我创造了这样的如何创建结构体的NSMutableArray?
typedef struct Node {
NSString* Description;
NSString* AE;
NSString* IP;
NSString* Port;
} Node;
我需要创建这个节点结构,我需要知道如何创建节点路径的目标是到NSMutableArray
检索和阅读,例如港口NSMutableArray
的结构。
我创造了这样的如何创建结构体的NSMutableArray?
typedef struct Node {
NSString* Description;
NSString* AE;
NSString* IP;
NSString* Port;
} Node;
我需要创建这个节点结构,我需要知道如何创建节点路径的目标是到NSMutableArray
检索和阅读,例如港口NSMutableArray
的结构。
只能在NSMutableArray
中存储Objective-C对象。可以采取
一种途径是使用一个标准的C数组:
unsigned int array_length = ...;
Node** nodes = malloc(sizeof(Node *) * array_length);
另一条路线是包装结构在一个Objective-C的对象:
@interface NodeWrapper : NSObject {
@public
Node *node;
}
- (id) initWithNode:(Node *) n;
@end
@implementation NodeWrapper
- (id) initWithNode:(Node *) n {
self = [super init];
if(self) {
node = n;
}
return self;
}
- (void) dealloc {
free(node);
[super dealloc];
}
@end
然后,你会添加NodeWrapper
对象的NSMutableArray
这样的:
Node *n = (Node *) malloc(sizeof(Node));
n->AE = @"blah";
NodeWrapper *nw = [[NodeWrapper alloc] initWithNode:n];
[myArray addObject:nw];
[nw release];
至RET rieve从NodeWrapper
的Node
,你只需做到这一点:
Node *n = nw->node;
或
Node n = *(nw->node);
实际上,你可以创建一个自定义类(因为它仅持有NSString
指针)与结构值作为实例变量。我认为它更有意义。
您还可以创建的NSValue
秒的阵列持有这些结构:
NSValue *structValue = [NSValue value:&myNode objCType:@encode(Node *)];
NSMutableArray *array = [[NSMutableArray alloc] initWithObject:structValue];
然后,您可以retreive这些结构如下:
NSValue *structValue = [array objectAtIndex:0];
Node *myNode = (Node *)[structValue pointerValue];
// or
Node myNode = *(Node *)[structValue pointerValue];
哇。我今天学到了东西。真棒! :-) – 2011-06-02 09:52:42
谢谢!很高兴你发现这个也很有用。) – Eimantas 2011-06-02 10:03:54
运行到这个问题后,我碰到这个线程的帮助,但比我最终解决方案更复杂。
基本上NSValue是你的结构的包装,你不需要自己创建一个新的类。
// To add your struct value to a NSMutableArray
NSValue *value = [NSValue valueWithBytes:&structValue objCType:@encode(MyStruct)];
[array addObject:value];
// To retrieve the stored value
MyStruct structValue;
NSValue *value = [array objectAtIndex:0];
[value getValue:&structValue];
我希望这个答案能够为下一个人节省一点时间。
+ 1给大家。 – 2012-11-09 08:02:33