Add and extract struct from NSMutableArray [duplic

2019-06-24 00:50发布

Possible Duplicate:
What’s the best way to put a c-struct in an NSArray?

I need to create an array of structures, such as:

typedef struct
{
    int fill;
    BOOL busy;
} MapCellST;

How can I add instances of this structure in NSMutableArray and how I can extract copies of the structure and work with its properties later?

3条回答
倾城 Initia
2楼-- · 2019-06-24 01:01

Wrap the struct in an NSValue:

MapCellSt x;
NSValue* value = [NSValue value:&x withObjCType:@encode(MapCellSt)];

To extract it later:

[value getValue:&x];
查看更多
成全新的幸福
3楼-- · 2019-06-24 01:05

Use NSMutableDictionary rather than NSMutableArray.

typedef struct {...} MyStruct;

NSMutableString* myKey = [NSMutableString stringWithString:@"MyKey"];
NSValue *myStructPtr = [NSValue value:&myStruct withObjCType:@encode( MyStruct )];
[myMutableDictionary setObject:myStructPtr forKey:myKey];
查看更多
forever°为你锁心
4楼-- · 2019-06-24 01:23

Ya can't.

Only real Obj-C objects can be added directly to NSMutableArray and friends; in order to do what you are describing you would have to create a class with the properties of the struct you are wanting to use.

Edit: As Tamás says, you can also use an NSValue; but in all likelihood creating a class for your MapCell is a better idea.

查看更多
登录 后发表回答