How can I create an NSMutableArray of structs?
I created a structure like this
typedef struct Node {
NSString* Description;
NSString* AE;
NSString* IP;
NSString* 开发者_运维知识库Port;
} Node;
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.
After running into this problem, I came across this thread which helped, but was more complicated than the solution I ended up with.
Basically the NSValue is the wrapper for your struct, you don't need to create a new class yourself.
// 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];
I hope this answer will save the next person a bit of time.
You can actually create a custom class (since it holds only NSString
pointers) with struct values as instance variables. I think it'd even make more sense.
You can also create an array of NSValue
s which hold these structures:
NSValue *structValue = [NSValue value:&myNode objCType:@encode(Node *)];
NSMutableArray *array = [[NSMutableArray alloc] initWithObject:structValue];
You can then retreive these structs as follows:
NSValue *structValue = [array objectAtIndex:0];
Node *myNode = (Node *)[structValue pointerValue];
// or
Node myNode = *(Node *)[structValue pointerValue];
You can only store Objective-C objects in an NSMutableArray
.
One route you can take is to use a standard C array:
unsigned int array_length = ...;
Node** nodes = malloc(sizeof(Node *) * array_length);
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
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];
To retrieve the Node
from the NodeWrapper
, you'd simply do this:
Node *n = nw->node;
or
Node n = *(nw->node);
精彩评论