【发布时间】: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 文档也显示了这个过程:
大家的共识似乎是通过 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