如何创建NSMutableArray结构?

AMH*_*AMH 11 objective-c

我创建了这样的结构

typedef struct Node {
    NSString* Description;
    NSString* AE;
    NSString* IP;
    NSString*  Port;
} Node;
Run Code Online (Sandbox Code Playgroud)

我需要创建NSMutableArray这个Node结构,我需要知道如何创建节点路径的对象来NSMutableArray检索它并读取例如端口.

Jim*_*ong 39

运行到这个问题后,我碰到这个线程这帮助,但比我结束了该解决方案更加复杂.

基本上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];
Run Code Online (Sandbox Code Playgroud)

我希望这个答案会为下一个人节省一点时间.


Eim*_*tas 13

实际上,您可以创建一个自定义类(因为它只包含NSString指针),并将struct值作为实例变量.我认为它甚至更有意义.

您还可以创建一个包含NSValue这些结构的s 数组:

NSValue *structValue = [NSValue value:&myNode objCType:@encode(Node *)];
NSMutableArray *array = [[NSMutableArray alloc] initWithObject:structValue];
Run Code Online (Sandbox Code Playgroud)

然后,您可以按如下方式检索这些结构:

NSValue *structValue = [array objectAtIndex:0];
Node *myNode = (Node *)[structValue pointerValue];
// or
Node myNode = *(Node *)[structValue pointerValue];
Run Code Online (Sandbox Code Playgroud)

  • 哇.我今天学到了一些东西 真棒!:-) (4认同)

Jac*_*kin 6

您只能将 Objective-C 对象存储在NSMutableArray.

您可以采用的一种方法是使用标准 C 数组:

unsigned int array_length = ...;
Node** nodes = malloc(sizeof(Node *) * array_length);
Run Code Online (Sandbox Code Playgroud)

另一种方法是将结构包装在一个 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
Run Code Online (Sandbox Code Playgroud)

然后,您NodeWrapper可以NSMutableArray 像这样添加对象:

Node *n = (Node *) malloc(sizeof(Node));
n->AE = @"blah";
NodeWrapper *nw = [[NodeWrapper alloc] initWithNode:n];
[myArray addObject:nw];
[nw release];
Run Code Online (Sandbox Code Playgroud)

为了取回NodeNodeWrapper,你只需做到这一点:

Node *n = nw->node;
Run Code Online (Sandbox Code Playgroud)

或者

Node n = *(nw->node);
Run Code Online (Sandbox Code Playgroud)