【问题标题】:Fetch Values from C-Struct in a NSMutableArray [duplicate]从 NSMutableArray 中的 C-Struct 中获取值
【发布时间】:2014-11-01 04:51:57
【问题描述】:

这个问题已经在 SO 中被问过几次,前两个答案是:

What's the best way to put a c-struct in an NSArray?

How can I create an NSMutableArray of structs?

Apple 文档也显示了这个过程:

https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/NumbersandValues/Articles/Values.html

大家的共识似乎是通过 NSValue 的方式将 struct 变成一个对象。遵循此建议时,我遇到的问题是,当我取回数据时,会得到虚假的结果。

我的结构很简单:

typedef struct { uint8_t r, g, b, a; } Pixel;

正如上面链接中所解释的,我可以将它添加到数组中

NSMutableArray *ledColors;

通过以下方式使用 NSValue:

    Pixel p_in = {0,0,0,1};
    NSLog(@"Pixel in: %d %d %d %d",p_in.r,p_in.g,p_in.b, p_in.a);

    NSValue *p_obj = [NSValue valueWithBytes:&p_in objCType:@encode(Pixel)];
//    NSValue *p_obj = [NSValue value:&p_in withObjCType:@encode(Pixel)]; //this seems to work too.


    for (int i=0; i<numLeds; i++) {
        [ledColors addObject:p_obj];
    }

但是,当我按照上面链接的帖子中所述检索/获取数据时,我没有得到原始的 {0,0,0,1} 而是随机整数:

    Pixel p_out;
    [[ledColors objectAtIndex:0] getValue:&p_out];

    // Doesn't return the correct data
    NSLog(@"Pixel out: %d %d %d %d",p_out.r,p_out.g,p_out.b, p_out.a); 

【问题讨论】:

  • 你需要调试代码。使用调试器通过代码查看每一步的值。为值添加 NSLog() 并找出问题所在。

标签: objective-c macos cocoa struct nsmutablearray


【解决方案1】:

我刚刚运行了下面的代码,一切正常,这让我觉得问题出在其他地方。

Pixel p_in = {0,0,0,1};
NSLog(@"Pixel in: %d %d %d %d",p_in.r,p_in.g,p_in.b, p_in.a);
NSValue* v_in = [NSValue valueWithBytes:&p_in objCType:@encode(Pixel)];

NSMutableArray* arr = [NSMutableArray array];
[arr addObject:v_in];

Pixel p_out = {3,3,3,3};
[[arr objectAtIndex:0] getValue:&p_out];
NSLog(@"Pixel out: %d %d %d %d",p_out.r,p_out.g,p_out.b, p_out.a);

我的猜测是,ledColorsnil,当您尝试取回对象时,这将无济于事,并在p_out 中留下未初始化的内存。

【讨论】:

  • 谢谢汤姆,就是这样。这段代码在我的 awakeFromNib 中运行,我没有添加 ledColors = [[NSMutableArray alloc] init];事先。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 2013-05-18
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多