【问题标题】:Add and extract struct from NSMutableArray [duplicate]从 NSMutableArray 添加和提取结构 [重复]
【发布时间】:2011-08-07 23:08:10
【问题描述】:

可能重复:
What’s the best way to put a c-struct in an NSArray?

我需要创建一个结构数组,例如:

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

如何在 NSMutableArray 中添加此结构的实例,以及如何提取结构的副本并在以后使用其属性?

【问题讨论】:

    标签: iphone struct nsarray


    【解决方案1】:

    将结构包装在NSValue:

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

    稍后提取:

    [value getValue:&x];
    

    【讨论】:

    • 我做了这个解决方案,但它给出了一个错误的访问错误
    【解决方案2】:

    使用NSMutableDictionary 而不是NSMutableArray

    typedef struct {...} MyStruct;

    NSMutableString* myKey = [NSMutableString stringWithString:@"MyKey"];
    NSValue *myStructPtr = [NSValue value:&myStruct withObjCType:@encode( MyStruct )];
    [myMutableDictionary setObject:myStructPtr forKey:myKey];
    

    【讨论】:

      【解决方案3】:

      你不能。

      只有真正的 Obj-C 对象才能直接添加到 NSMutableArray 和好友中;为了执行您所描述的操作,您必须使用您要使用的结构的属性创建一个类。

      编辑: 正如 Tamás 所说,您也可以使用 NSValue;但很可能为您的 MapCell 创建一个类是一个更好的主意。

      【讨论】:

        猜你喜欢
        • 2013-02-09
        • 1970-01-01
        • 1970-01-01
        • 2013-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-22
        • 2011-12-08
        相关资源
        最近更新 更多