如何创建结构的NSMutableArray? [英] How can I create an NSMutableArray of structs?
问题描述
我创建了这样的结构
typedef struct Node {
NSString* Description;
NSString* AE;
NSString* IP;
NSString* Port;
} Node;
我需要创建此Node结构的NSMutableArray
,我需要知道如何将节点的对象创建到NSMutableArray
的路径检索它并读取例如端口.
I need to create NSMutableArray
of this Node structure I need to know how create object of node path it to the NSMutableArray
retrieve it and read for example the port.
推荐答案
您只能将Objective-C对象存储在NSMutableArray
中.
You can only store Objective-C objects in an NSMutableArray
.
您可以采取的一种方法是使用标准C数组:
One route you can take is to use a standard C array:
unsigned int array_length = ...;
Node** nodes = malloc(sizeof(Node *) * array_length);
另一种方法是将结构包装在Objective-C对象中:
Another route is to wrap the structure in an Objective-C object:
@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
中,如下所示:
Then, you'd add NodeWrapper
objects to your NSMutableArray
like this:
Node *n = (Node *) malloc(sizeof(Node));
n->AE = @"blah";
NodeWrapper *nw = [[NodeWrapper alloc] initWithNode:n];
[myArray addObject:nw];
[nw release];
要从NodeWrapper
中检索Node
,只需执行以下操作:
To retrieve the Node
from the NodeWrapper
, you'd simply do this:
Node *n = nw->node;
或
Node n = *(nw->node);
这篇关于如何创建结构的NSMutableArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!