【问题标题】:Cocoa structs and NSMutableArrayCocoa 结构和 NSMutableArray
【发布时间】:2010-06-01 02:32:40
【问题描述】:

我有一个 NSMutableArray,我正在尝试存储和访问一些结构。我该怎么做呢? 'addObject' 给我一个错误,说“addObject 的参数 1 的类型不兼容”。下面是一个例子('in' 是一个 NSFileHandle,'array' 是 NSMutableArray):

//Write points
for(int i=0; i<5; i++) {
    struct Point p;
    buff = [in readDataOfLength:1];
    [buff getBytes:&(p.x) length:sizeof(p.x)];
    [array addObject:p];
}

//Read points
for(int i=0; i<5; i++) {
    struct Point p = [array objectAtIndex:i];
    NSLog(@"%i", p.x);
}

【问题讨论】:

    标签: cocoa nsmutablearray struct


    【解决方案1】:

    如前所述,NSValue 可以使用+value:withObjCType:-initWithBytes:objCType: 包装一个普通结构:

    // add:
    [array addObject:[NSValue value:&p withObjCType:@encode(struct Point)]];
    
    // extract:
    struct Point p;
    [[array objectAtIndex:i] getValue:&p];
    

    有关更多示例,请参阅Number and Value guide

    【讨论】:

    • 我不知道你是谁,但我会找到你,给你喝啤酒!
    【解决方案2】:

    您收到错误是因为NSMutableArray 只能接受对对象的引用,因此您应该将您的结构包装在一个类中:

    @interface PointClass {
         struct Point p;
    }
    
    @property (nonatomic, assign) struct Point p;
    

    这样,您可以传入PointClass 的实例。

    编辑:正如上面和下面提到的,NSValue 已经以更通用的方式提供了这一点,所以你应该这样做。

    【讨论】:

      【解决方案3】:

      您可以使用 NSValue,或者在某些情况下使用字典代替结构可能更有意义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-07
        • 1970-01-01
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多