Add and extract struct from NSMutableArray [duplicate]

回眸只為那壹抹淺笑 提交于 2019-12-10 15:38:47

问题


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?


回答1:


Wrap the struct in an NSValue:

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

To extract it later:

[value getValue:&x];



回答2:


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];



回答3:


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.



来源:https://stackoverflow.com/questions/5704722/add-and-extract-struct-from-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!